1 /*
   2  * Copyright (c) 1997, 2011, 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 #ifndef SHARE_VM_MEMORY_ALLOCATION_HPP
  26 #define SHARE_VM_MEMORY_ALLOCATION_HPP
  27 
  28 #include "runtime/globals.hpp"
  29 #include "utilities/globalDefinitions.hpp"
  30 #ifdef COMPILER1
  31 #include "c1/c1_globals.hpp"
  32 #endif
  33 #ifdef COMPILER2
  34 #include "opto/c2_globals.hpp"
  35 #endif
  36 
  37 #include <new>
  38 
  39 #define ARENA_ALIGN_M1 (((size_t)(ARENA_AMALLOC_ALIGNMENT)) - 1)
  40 #define ARENA_ALIGN_MASK (~((size_t)ARENA_ALIGN_M1))
  41 #define ARENA_ALIGN(x) ((((size_t)(x)) + ARENA_ALIGN_M1) & ARENA_ALIGN_MASK)
  42 
  43 // All classes in the virtual machine must be subclassed
  44 // by one of the following allocation classes:
  45 //
  46 // For objects allocated in the resource area (see resourceArea.hpp).
  47 // - ResourceObj
  48 //
  49 // For objects allocated in the C-heap (managed by: free & malloc).
  50 // - CHeapObj
  51 //
  52 // For objects allocated on the stack.
  53 // - StackObj
  54 //
  55 // For embedded objects.
  56 // - ValueObj
  57 //
  58 // For classes used as name spaces.
  59 // - AllStatic
  60 //
  61 // The printable subclasses are used for debugging and define virtual
  62 // member functions for printing. Classes that avoid allocating the
  63 // vtbl entries in the objects should therefore not be the printable
  64 // subclasses.
  65 //
  66 // The following macros and function should be used to allocate memory
  67 // directly in the resource area or in the C-heap:
  68 //
  69 //   NEW_RESOURCE_ARRAY(type,size)
  70 //   NEW_RESOURCE_OBJ(type)
  71 //   NEW_C_HEAP_ARRAY(type,size)
  72 //   NEW_C_HEAP_OBJ(type)
  73 //   char* AllocateHeap(size_t size, const char* name);
  74 //   void  FreeHeap(void* p);
  75 //
  76 // C-heap allocation can be traced using +PrintHeapAllocation.
  77 // malloc and free should therefore never called directly.
  78 
  79 // Base class for objects allocated in the C-heap.
  80 
  81 // In non product mode we introduce a super class for all allocation classes
  82 // that supports printing.
  83 // We avoid the superclass in product mode since some C++ compilers add
  84 // a word overhead for empty super classes.
  85 
  86 #ifdef PRODUCT
  87 #define ALLOCATION_SUPER_CLASS_SPEC
  88 #else
  89 #define ALLOCATION_SUPER_CLASS_SPEC : public AllocatedObj
  90 class AllocatedObj {
  91  public:
  92   // Printing support
  93   void print() const;
  94   void print_value() const;
  95 
  96   virtual void print_on(outputStream* st) const;
  97   virtual void print_value_on(outputStream* st) const;
  98 };
  99 #endif
 100 
 101 class CHeapObj ALLOCATION_SUPER_CLASS_SPEC {
 102  public:
 103   void* operator new(size_t size);
 104   void* operator new (size_t size, const std::nothrow_t&  nothrow_constant);
 105   void  operator delete(void* p);
 106   void* new_array(size_t size);
 107 };
 108 
 109 // Base class for objects allocated on the stack only.
 110 // Calling new or delete will result in fatal error.
 111 
 112 class StackObj ALLOCATION_SUPER_CLASS_SPEC {
 113  public:
 114   void* operator new(size_t size);
 115   void  operator delete(void* p);
 116 };
 117 
 118 // Base class for objects used as value objects.
 119 // Calling new or delete will result in fatal error.
 120 //
 121 // Portability note: Certain compilers (e.g. gcc) will
 122 // always make classes bigger if it has a superclass, even
 123 // if the superclass does not have any virtual methods or
 124 // instance fields. The HotSpot implementation relies on this
 125 // not to happen. So never make a ValueObj class a direct subclass
 126 // of this object, but use the VALUE_OBJ_CLASS_SPEC class instead, e.g.,
 127 // like this:
 128 //
 129 //   class A VALUE_OBJ_CLASS_SPEC {
 130 //     ...
 131 //   }
 132 //
 133 // With gcc and possible other compilers the VALUE_OBJ_CLASS_SPEC can
 134 // be defined as a an empty string "".
 135 //
 136 class _ValueObj {
 137  public:
 138   void* operator new(size_t size);
 139   void operator delete(void* p);
 140 };
 141 
 142 // Base class for classes that constitute name spaces.
 143 
 144 class AllStatic {
 145  public:
 146   AllStatic()  { ShouldNotCallThis(); }
 147   ~AllStatic() { ShouldNotCallThis(); }
 148 };
 149 
 150 
 151 //------------------------------Chunk------------------------------------------
 152 // Linked list of raw memory chunks
 153 class Chunk: public CHeapObj {
 154  protected:
 155   Chunk*       _next;     // Next Chunk in list
 156   const size_t _len;      // Size of this Chunk
 157  public:
 158   void* operator new(size_t size, size_t length);
 159   void  operator delete(void* p);
 160   Chunk(size_t length);
 161 
 162   enum {
 163     // default sizes; make them slightly smaller than 2**k to guard against
 164     // buddy-system style malloc implementations
 165 #ifdef _LP64
 166     slack      = 40,            // [RGV] Not sure if this is right, but make it
 167                                 //       a multiple of 8.
 168 #else
 169     slack      = 20,            // suspected sizeof(Chunk) + internal malloc headers
 170 #endif
 171 
 172     init_size  =  1*K  - slack, // Size of first chunk
 173     medium_size= 10*K  - slack, // Size of medium-sized chunk
 174     size       = 32*K  - slack, // Default size of an Arena chunk (following the first)
 175     non_pool_size = init_size + 32 // An initial size which is not one of above
 176   };
 177 
 178   void chop();                  // Chop this chunk
 179   void next_chop();             // Chop next chunk
 180   static size_t aligned_overhead_size(void) { return ARENA_ALIGN(sizeof(Chunk)); }
 181 
 182   size_t length() const         { return _len;  }
 183   Chunk* next() const           { return _next;  }
 184   void set_next(Chunk* n)       { _next = n;  }
 185   // Boundaries of data area (possibly unused)
 186   char* bottom() const          { return ((char*) this) + aligned_overhead_size();  }
 187   char* top()    const          { return bottom() + _len; }
 188   bool contains(char* p) const  { return bottom() <= p && p <= top(); }
 189 
 190   // Start the chunk_pool cleaner task
 191   static void start_chunk_pool_cleaner_task();
 192 
 193   static void clean_chunk_pool();
 194 };
 195 
 196 //------------------------------Arena------------------------------------------
 197 // Fast allocation of memory
 198 class Arena: public CHeapObj {
 199 protected:
 200   friend class ResourceMark;
 201   friend class HandleMark;
 202   friend class NoHandleMark;
 203   Chunk *_first;                // First chunk
 204   Chunk *_chunk;                // current chunk
 205   char *_hwm, *_max;            // High water mark and max in current chunk
 206   void* grow(size_t x);         // Get a new Chunk of at least size x
 207   NOT_PRODUCT(size_t _size_in_bytes;) // Size of arena (used for memory usage tracing)
 208   NOT_PRODUCT(static julong _bytes_allocated;) // total #bytes allocated since start
 209   friend class AllocStats;
 210   debug_only(void* malloc(size_t size);)
 211   debug_only(void* internal_malloc_4(size_t x);)
 212   NOT_PRODUCT(void inc_bytes_allocated(size_t x);)
 213 
 214   void signal_out_of_memory(size_t request, const char* whence) const;
 215 
 216   void check_for_overflow(size_t request, const char* whence) const {
 217     if (UINTPTR_MAX - request < (uintptr_t)_hwm) {
 218       signal_out_of_memory(request, whence);
 219     }
 220  }
 221 
 222  public:
 223   Arena();
 224   Arena(size_t init_size);
 225   Arena(Arena *old);
 226   ~Arena();
 227   void  destruct_contents();
 228   char* hwm() const             { return _hwm; }
 229 
 230   // Fast allocate in the arena.  Common case is: pointer test + increment.
 231   void* Amalloc(size_t x) {
 232     assert(is_power_of_2(ARENA_AMALLOC_ALIGNMENT) , "should be a power of 2");
 233     x = ARENA_ALIGN(x);
 234     debug_only(if (UseMallocOnly) return malloc(x);)
 235     check_for_overflow(x, "Arena::Amalloc");
 236     NOT_PRODUCT(inc_bytes_allocated(x);)
 237     if (_hwm + x > _max) {
 238       return grow(x);
 239     } else {
 240       char *old = _hwm;
 241       _hwm += x;
 242       return old;
 243     }
 244   }
 245   // Further assume size is padded out to words
 246   void *Amalloc_4(size_t x) {
 247     assert( (x&(sizeof(char*)-1)) == 0, "misaligned size" );
 248     debug_only(if (UseMallocOnly) return malloc(x);)
 249     check_for_overflow(x, "Arena::Amalloc_4");
 250     NOT_PRODUCT(inc_bytes_allocated(x);)
 251     if (_hwm + x > _max) {
 252       return grow(x);
 253     } else {
 254       char *old = _hwm;
 255       _hwm += x;
 256       return old;
 257     }
 258   }
 259 
 260   // Allocate with 'double' alignment. It is 8 bytes on sparc.
 261   // In other cases Amalloc_D() should be the same as Amalloc_4().
 262   void* Amalloc_D(size_t x) {
 263     assert( (x&(sizeof(char*)-1)) == 0, "misaligned size" );
 264     debug_only(if (UseMallocOnly) return malloc(x);)
 265 #if defined(SPARC) && !defined(_LP64)
 266 #define DALIGN_M1 7
 267     size_t delta = (((size_t)_hwm + DALIGN_M1) & ~DALIGN_M1) - (size_t)_hwm;
 268     x += delta;
 269 #endif
 270     check_for_overflow(x, "Arena::Amalloc_D");
 271     NOT_PRODUCT(inc_bytes_allocated(x);)
 272     if (_hwm + x > _max) {
 273       return grow(x); // grow() returns a result aligned >= 8 bytes.
 274     } else {
 275       char *old = _hwm;
 276       _hwm += x;
 277 #if defined(SPARC) && !defined(_LP64)
 278       old += delta; // align to 8-bytes
 279 #endif
 280       return old;
 281     }
 282   }
 283 
 284   // Fast delete in area.  Common case is: NOP (except for storage reclaimed)
 285   void Afree(void *ptr, size_t size) {
 286 #ifdef ASSERT
 287     if (ZapResourceArea) memset(ptr, badResourceValue, size); // zap freed memory
 288     if (UseMallocOnly) return;
 289 #endif
 290     if (((char*)ptr) + size == _hwm) _hwm = (char*)ptr;
 291   }
 292 
 293   void *Arealloc( void *old_ptr, size_t old_size, size_t new_size );
 294 
 295   // Move contents of this arena into an empty arena
 296   Arena *move_contents(Arena *empty_arena);
 297 
 298   // Determine if pointer belongs to this Arena or not.
 299   bool contains( const void *ptr ) const;
 300 
 301   // Total of all chunks in use (not thread-safe)
 302   size_t used() const;
 303 
 304   // Total # of bytes used
 305   size_t size_in_bytes() const         NOT_PRODUCT({  return _size_in_bytes; }) PRODUCT_RETURN0;
 306   void set_size_in_bytes(size_t size)  NOT_PRODUCT({ _size_in_bytes = size;  }) PRODUCT_RETURN;
 307   static void free_malloced_objects(Chunk* chunk, char* hwm, char* max, char* hwm2)  PRODUCT_RETURN;
 308   static void free_all(char** start, char** end)                                     PRODUCT_RETURN;
 309 
 310 private:
 311   // Reset this Arena to empty, access will trigger grow if necessary
 312   void   reset(void) {
 313     _first = _chunk = NULL;
 314     _hwm = _max = NULL;
 315   }
 316 };
 317 
 318 // One of the following macros must be used when allocating
 319 // an array or object from an arena
 320 #define NEW_ARENA_ARRAY(arena, type, size) \
 321   (type*) (arena)->Amalloc((size) * sizeof(type))
 322 
 323 #define REALLOC_ARENA_ARRAY(arena, type, old, old_size, new_size)    \
 324   (type*) (arena)->Arealloc((char*)(old), (old_size) * sizeof(type), \
 325                             (new_size) * sizeof(type) )
 326 
 327 #define FREE_ARENA_ARRAY(arena, type, old, size) \
 328   (arena)->Afree((char*)(old), (size) * sizeof(type))
 329 
 330 #define NEW_ARENA_OBJ(arena, type) \
 331   NEW_ARENA_ARRAY(arena, type, 1)
 332 
 333 
 334 //%note allocation_1
 335 extern char* resource_allocate_bytes(size_t size);
 336 extern char* resource_allocate_bytes(Thread* thread, size_t size);
 337 extern char* resource_reallocate_bytes( char *old, size_t old_size, size_t new_size);
 338 extern void resource_free_bytes( char *old, size_t size );
 339 
 340 //----------------------------------------------------------------------
 341 // Base class for objects allocated in the resource area per default.
 342 // Optionally, objects may be allocated on the C heap with
 343 // new(ResourceObj::C_HEAP) Foo(...) or in an Arena with new (&arena)
 344 // ResourceObj's can be allocated within other objects, but don't use
 345 // new or delete (allocation_type is unknown).  If new is used to allocate,
 346 // use delete to deallocate.
 347 class ResourceObj ALLOCATION_SUPER_CLASS_SPEC {
 348  public:
 349   enum allocation_type { STACK_OR_EMBEDDED = 0, RESOURCE_AREA, C_HEAP, ARENA, allocation_mask = 0x3 };
 350   static void set_allocation_type(address res, allocation_type type) NOT_DEBUG_RETURN;
 351 #ifdef ASSERT
 352  private:
 353   // When this object is allocated on stack the new() operator is not
 354   // called but garbage on stack may look like a valid allocation_type.
 355   // Store negated 'this' pointer when new() is called to distinguish cases.
 356   // Use second array's element for verification value to distinguish garbage.
 357   uintptr_t _allocation_t[2];
 358   bool is_type_set() const;
 359  public:
 360   allocation_type get_allocation_type() const;
 361   bool allocated_on_stack()    const { return get_allocation_type() == STACK_OR_EMBEDDED; }
 362   bool allocated_on_res_area() const { return get_allocation_type() == RESOURCE_AREA; }
 363   bool allocated_on_C_heap()   const { return get_allocation_type() == C_HEAP; }
 364   bool allocated_on_arena()    const { return get_allocation_type() == ARENA; }
 365   ResourceObj(); // default construtor
 366   ResourceObj(const ResourceObj& r); // default copy construtor
 367   ResourceObj& operator=(const ResourceObj& r); // default copy assignment
 368   ~ResourceObj();
 369 #endif // ASSERT
 370 
 371  public:
 372   void* operator new(size_t size, allocation_type type);
 373   void* operator new(size_t size, Arena *arena) {
 374       address res = (address)arena->Amalloc(size);
 375       DEBUG_ONLY(set_allocation_type(res, ARENA);)
 376       return res;
 377   }
 378   void* operator new(size_t size) {
 379       address res = (address)resource_allocate_bytes(size);
 380       DEBUG_ONLY(set_allocation_type(res, RESOURCE_AREA);)
 381       return res;
 382   }
 383   void  operator delete(void* p);
 384 };
 385 
 386 // One of the following macros must be used when allocating an array
 387 // or object to determine whether it should reside in the C heap on in
 388 // the resource area.
 389 
 390 #define NEW_RESOURCE_ARRAY(type, size)\
 391   (type*) resource_allocate_bytes((size) * sizeof(type))
 392 
 393 #define NEW_RESOURCE_ARRAY_IN_THREAD(thread, type, size)\
 394   (type*) resource_allocate_bytes(thread, (size) * sizeof(type))
 395 
 396 #define REALLOC_RESOURCE_ARRAY(type, old, old_size, new_size)\
 397   (type*) resource_reallocate_bytes((char*)(old), (old_size) * sizeof(type), (new_size) * sizeof(type) )
 398 
 399 #define FREE_RESOURCE_ARRAY(type, old, size)\
 400   resource_free_bytes((char*)(old), (size) * sizeof(type))
 401 
 402 #define FREE_FAST(old)\
 403     /* nop */
 404 
 405 #define NEW_RESOURCE_OBJ(type)\
 406   NEW_RESOURCE_ARRAY(type, 1)
 407 
 408 #define NEW_C_HEAP_ARRAY(type, size)\
 409   (type*) (AllocateHeap((size) * sizeof(type), XSTR(type) " in " __FILE__))
 410 
 411 #define REALLOC_C_HEAP_ARRAY(type, old, size)\
 412   (type*) (ReallocateHeap((char*)old, (size) * sizeof(type), XSTR(type) " in " __FILE__))
 413 
 414 #define FREE_C_HEAP_ARRAY(type,old) \
 415   FreeHeap((char*)(old))
 416 
 417 #define NEW_C_HEAP_OBJ(type)\
 418   NEW_C_HEAP_ARRAY(type, 1)
 419 
 420 extern bool warn_new_operator;
 421 
 422 // for statistics
 423 #ifndef PRODUCT
 424 class AllocStats : StackObj {
 425   julong start_mallocs, start_frees;
 426   julong start_malloc_bytes, start_mfree_bytes, start_res_bytes;
 427  public:
 428   AllocStats();
 429 
 430   julong num_mallocs();    // since creation of receiver
 431   julong alloc_bytes();
 432   julong num_frees();
 433   julong free_bytes();
 434   julong resource_bytes();
 435   void   print();
 436 };
 437 #endif
 438 
 439 
 440 //------------------------------ReallocMark---------------------------------
 441 // Code which uses REALLOC_RESOURCE_ARRAY should check an associated
 442 // ReallocMark, which is declared in the same scope as the reallocated
 443 // pointer.  Any operation that could __potentially__ cause a reallocation
 444 // should check the ReallocMark.
 445 class ReallocMark: public StackObj {
 446 protected:
 447   NOT_PRODUCT(int _nesting;)
 448 
 449 public:
 450   ReallocMark()   PRODUCT_RETURN;
 451   void check()    PRODUCT_RETURN;
 452 };
 453 
 454 #endif // SHARE_VM_MEMORY_ALLOCATION_HPP