allocation.h 10.1 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_UTILS_ALLOCATION_H_
#define V8_UTILS_ALLOCATION_H_
7

8
#include "include/v8-platform.h"
9
#include "src/base/address-region.h"
10
#include "src/base/compiler-specific.h"
11
#include "src/base/platform/platform.h"
12 13
#include "src/common/globals.h"
#include "src/init/v8.h"
14

15 16
namespace v8 {
namespace internal {
17

18 19
class Isolate;

20 21 22 23 24 25
// This file defines memory allocation functions. If a first attempt at an
// allocation fails, these functions call back into the embedder, then attempt
// the allocation a second time. The embedder callback must not reenter V8.

// Called when allocation routines fail to allocate, even with a possible retry.
// This function should not return, but should terminate the current processing.
26
[[noreturn]] V8_EXPORT_PRIVATE void FatalProcessOutOfMemory(
27
    Isolate* isolate, const char* message);
28 29

// Superclass for classes managed with new & delete.
30
class V8_EXPORT_PRIVATE Malloced {
31
 public:
32 33
  static void* operator new(size_t size);
  static void operator delete(void* p);
34 35 36
};

template <typename T>
37
T* NewArray(size_t size) {
38 39
  T* result = new (std::nothrow) T[size];
  if (result == nullptr) {
40
    V8::GetCurrentPlatform()->OnCriticalMemoryPressure();
41
    result = new (std::nothrow) T[size];
42
    if (result == nullptr) FatalProcessOutOfMemory(nullptr, "NewArray");
43
  }
44
  return result;
45 46
}

47 48
template <typename T, typename = typename std::enable_if<
                          base::is_trivially_copyable<T>::value>::type>
49 50 51 52 53 54
T* NewArray(size_t size, T default_val) {
  T* result = reinterpret_cast<T*>(NewArray<uint8_t>(sizeof(T) * size));
  for (size_t i = 0; i < size; ++i) result[i] = default_val;
  return result;
}

55
template <typename T>
56
void DeleteArray(T* array) {
57 58 59
  delete[] array;
}

60 61 62
// The normal strdup functions use malloc.  These versions of StrDup
// and StrNDup uses new and calls the FatalProcessOutOfMemory handler
// if allocation fails.
63
V8_EXPORT_PRIVATE char* StrDup(const char* str);
64
char* StrNDup(const char* str, int n);
65 66 67 68 69

// Allocation policy for allocating in the C free store using malloc
// and free. Used as the default policy for lists.
class FreeStoreAllocationPolicy {
 public:
70 71 72 73 74 75 76 77
  template <typename T, typename TypeTag = T[]>
  V8_INLINE T* NewArray(size_t length) {
    return static_cast<T*>(Malloced::operator new(length * sizeof(T)));
  }
  template <typename T, typename TypeTag = T[]>
  V8_INLINE void DeleteArray(T* p, size_t length) {
    Malloced::operator delete(p);
  }
78 79
};

80 81 82
// Performs a malloc, with retry logic on failure. Returns nullptr on failure.
// Call free to release memory allocated with this function.
void* AllocWithRetry(size_t size);
83

84
V8_EXPORT_PRIVATE void* AlignedAlloc(size_t size, size_t alignment);
85
V8_EXPORT_PRIVATE void AlignedFree(void* ptr);
86

87 88 89
// Returns platfrom page allocator instance. Guaranteed to be a valid pointer.
V8_EXPORT_PRIVATE v8::PageAllocator* GetPlatformPageAllocator();

90 91 92 93 94 95 96
// Sets the given page allocator as the platform page allocator and returns
// the current one. This function *must* be used only for testing purposes.
// It is not thread-safe and the testing infrastructure should ensure that
// the tests do not modify the value simultaneously.
V8_EXPORT_PRIVATE v8::PageAllocator* SetPlatformPageAllocatorForTesting(
    v8::PageAllocator* page_allocator);

97
// Gets the page granularity for AllocatePages and FreePages. Addresses returned
98
// by AllocatePages are aligned to this size.
99 100 101 102 103
V8_EXPORT_PRIVATE size_t AllocatePageSize();

// Gets the granularity at which the permissions and release calls can be made.
V8_EXPORT_PRIVATE size_t CommitPageSize();

104 105
// Sets the random seed so that GetRandomMmapAddr() will generate repeatable
// sequences of random mmap addresses.
106 107
V8_EXPORT_PRIVATE void SetRandomMmapSeed(int64_t seed);

108 109 110 111 112 113 114 115
// Generate a random address to be used for hinting allocation calls.
V8_EXPORT_PRIVATE void* GetRandomMmapAddr();

// Allocates memory. Permissions are set according to the access argument.
// |address| is a hint. |size| and |alignment| must be multiples of
// AllocatePageSize(). Returns the address of the allocated memory, with the
// specified size and alignment, or nullptr on failure.
V8_EXPORT_PRIVATE
116 117
V8_WARN_UNUSED_RESULT void* AllocatePages(v8::PageAllocator* page_allocator,
                                          void* address, size_t size,
118
                                          size_t alignment,
119
                                          PageAllocator::Permission access);
120 121 122 123

// Frees memory allocated by a call to AllocatePages. |address| and |size| must
// be multiples of AllocatePageSize(). Returns true on success, otherwise false.
V8_EXPORT_PRIVATE
124 125
V8_WARN_UNUSED_RESULT bool FreePages(v8::PageAllocator* page_allocator,
                                     void* address, const size_t size);
126 127 128 129 130 131 132

// Releases memory that is no longer needed. The range specified by |address|
// and |size| must be an allocated memory region. |size| and |new_size| must be
// multiples of CommitPageSize(). Memory from |new_size| to |size| is released.
// Released memory is left in an undefined state, so it should not be accessed.
// Returns true on success, otherwise false.
V8_EXPORT_PRIVATE
133 134
V8_WARN_UNUSED_RESULT bool ReleasePages(v8::PageAllocator* page_allocator,
                                        void* address, size_t size,
135 136 137 138 139 140 141
                                        size_t new_size);

// Sets permissions according to |access|. |address| and |size| must be
// multiples of CommitPageSize(). Setting permission to kNoAccess may
// cause the memory contents to be lost. Returns true on success, otherwise
// false.
V8_EXPORT_PRIVATE
142 143
V8_WARN_UNUSED_RESULT bool SetPermissions(v8::PageAllocator* page_allocator,
                                          void* address, size_t size,
144
                                          PageAllocator::Permission access);
145 146 147 148
inline bool SetPermissions(v8::PageAllocator* page_allocator, Address address,
                           size_t size, PageAllocator::Permission access) {
  return SetPermissions(page_allocator, reinterpret_cast<void*>(address), size,
                        access);
149
}
150

151 152 153 154 155
// Function that may release reserved memory regions to allow failed allocations
// to succeed. |length| is the amount of memory needed. Returns |true| if memory
// could be released, false otherwise.
V8_EXPORT_PRIVATE bool OnCriticalMemoryPressure(size_t length);

156
// Represents and controls an area of reserved memory.
157
class VirtualMemory final {
158
 public:
159 160
  enum JitPermission { kNoJit, kMapAsJittable };

161
  // Empty VirtualMemory object, controlling no reserved memory.
162
  V8_EXPORT_PRIVATE VirtualMemory();
163

164 165 166
  VirtualMemory(const VirtualMemory&) = delete;
  VirtualMemory& operator=(const VirtualMemory&) = delete;

167
  // Reserves virtual memory containing an area of the given size that is
168
  // aligned per |alignment| rounded up to the |page_allocator|'s allocate page
169
  // size. The |size| must be aligned with |page_allocator|'s commit page size.
170
  // This may not be at the position returned by address().
171
  V8_EXPORT_PRIVATE VirtualMemory(v8::PageAllocator* page_allocator,
172 173
                                  size_t size, void* hint, size_t alignment = 1,
                                  JitPermission jit = kNoJit);
174 175 176

  // Construct a virtual memory by assigning it some already mapped address
  // and size.
177
  VirtualMemory(v8::PageAllocator* page_allocator, Address address, size_t size)
178
      : page_allocator_(page_allocator), region_(address, size) {
179
    DCHECK_NOT_NULL(page_allocator);
180 181
    DCHECK(IsAligned(address, page_allocator->AllocatePageSize()));
    DCHECK(IsAligned(size, page_allocator->CommitPageSize()));
182
  }
183 184 185

  // Releases the reserved memory, if any, controlled by this VirtualMemory
  // object.
186
  V8_EXPORT_PRIVATE ~VirtualMemory();
187

188
  // Move constructor.
189
  VirtualMemory(VirtualMemory&& other) V8_NOEXCEPT { *this = std::move(other); }
190 191 192

  // Move assignment operator.
  VirtualMemory& operator=(VirtualMemory&& other) V8_NOEXCEPT {
193 194 195 196
    DCHECK(!IsReserved());
    page_allocator_ = other.page_allocator_;
    region_ = other.region_;
    other.Reset();
197 198 199
    return *this;
  }

200
  // Returns whether the memory has been reserved.
201
  bool IsReserved() const { return region_.begin() != kNullAddress; }
202 203

  // Initialize or resets an embedded VirtualMemory object.
204
  V8_EXPORT_PRIVATE void Reset();
205

206 207
  v8::PageAllocator* page_allocator() { return page_allocator_; }

208
  base::AddressRegion region() const { return region_; }
209

210 211 212 213
  // Returns the start address of the reserved memory.
  // If the memory was reserved with an alignment, this address is not
  // necessarily aligned. The user might need to round it up to a multiple of
  // the alignment to get the start of the aligned block.
214
  Address address() const {
215
    DCHECK(IsReserved());
216
    return region_.begin();
217 218
  }

219
  Address end() const {
220
    DCHECK(IsReserved());
221
    return region_.end();
222 223 224 225 226 227
  }

  // Returns the size of the reserved memory. The returned value is only
  // meaningful when IsReserved() returns true.
  // If the memory was reserved with an alignment, this size may be larger
  // than the requested size.
228
  size_t size() const { return region_.size(); }
229

230 231
  // Sets permissions according to the access argument. address and size must be
  // multiples of CommitPageSize(). Returns true on success, otherwise false.
232 233
  V8_EXPORT_PRIVATE bool SetPermissions(Address address, size_t size,
                                        PageAllocator::Permission access);
234

235
  // Releases memory after |free_start|. Returns the number of bytes released.
236
  V8_EXPORT_PRIVATE size_t Release(Address free_start);
237

238
  // Frees all memory.
239
  V8_EXPORT_PRIVATE void Free();
240

241 242 243 244
  // As with Free but does not write to the VirtualMemory object itself so it
  // can be called on a VirtualMemory that is itself not writable.
  V8_EXPORT_PRIVATE void FreeReadOnly();

245
  bool InVM(Address address, size_t size) {
246
    return region_.contains(address, size);
247 248 249
  }

 private:
250
  // Page allocator that controls the virtual memory.
251
  v8::PageAllocator* page_allocator_ = nullptr;
252
  base::AddressRegion region_;
253 254
};

255 256
}  // namespace internal
}  // namespace v8
257

258
#endif  // V8_UTILS_ALLOCATION_H_