1 // Copyright 2012 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef V8_ALLOCATION_H_ 6 #define V8_ALLOCATION_H_ 7 8 #include "src/globals.h" 9 10 namespace v8 { 11 namespace internal { 12 13 // Called when allocation routines fail to allocate. 14 // This function should not return, but should terminate the current 15 // processing. 16 void FatalProcessOutOfMemory(const char* message); 17 18 // Superclass for classes managed with new & delete. 19 class Malloced { 20 public: 21 void* operator new(size_t size) { return New(size); } 22 void operator delete(void* p) { Delete(p); } 23 24 static void* New(size_t size); 25 static void Delete(void* p); 26 }; 27 28 29 // A macro is used for defining the base class used for embedded instances. 30 // The reason is some compilers allocate a minimum of one word for the 31 // superclass. The macro prevents the use of new & delete in debug mode. 32 // In release mode we are not willing to pay this overhead. 33 34 #ifdef DEBUG 35 // Superclass for classes with instances allocated inside stack 36 // activations or inside other objects. 37 class Embedded { 38 public: 39 void* operator new(size_t size); 40 void operator delete(void* p); 41 }; 42 #define BASE_EMBEDDED : public Embedded 43 #else 44 #define BASE_EMBEDDED 45 #endif 46 47 48 // Superclass for classes only using statics. 49 class AllStatic { 50 #ifdef DEBUG 51 public: 52 void* operator new(size_t size); 53 void operator delete(void* p); 54 #endif 55 }; 56 57 58 template <typename T> 59 T* NewArray(size_t size) { 60 T* result = new T[size]; 61 if (result == NULL) FatalProcessOutOfMemory("NewArray"); 62 return result; 63 } 64 65 66 template <typename T> 67 void DeleteArray(T* array) { 68 delete[] array; 69 } 70 71 72 // The normal strdup functions use malloc. These versions of StrDup 73 // and StrNDup uses new and calls the FatalProcessOutOfMemory handler 74 // if allocation fails. 75 char* StrDup(const char* str); 76 char* StrNDup(const char* str, int n); 77 78 79 // Allocation policy for allocating in the C free store using malloc 80 // and free. Used as the default policy for lists. 81 class FreeStoreAllocationPolicy { 82 public: 83 INLINE(void* New(size_t size)) { return Malloced::New(size); } 84 INLINE(static void Delete(void* p)) { Malloced::Delete(p); } 85 }; 86 87 88 void* AlignedAlloc(size_t size, size_t alignment); 89 void AlignedFree(void *ptr); 90 91 } // namespace internal 92 } // namespace v8 93 94 #endif // V8_ALLOCATION_H_ 95