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