allocation.h 9.93 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 159
 public:
  // Empty VirtualMemory object, controlling no reserved memory.
160
  V8_EXPORT_PRIVATE VirtualMemory();
161

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

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

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

183
  // Move constructor.
184
  VirtualMemory(VirtualMemory&& other) V8_NOEXCEPT { *this = std::move(other); }
185 186 187

  // Move assignment operator.
  VirtualMemory& operator=(VirtualMemory&& other) V8_NOEXCEPT {
188 189 190 191
    DCHECK(!IsReserved());
    page_allocator_ = other.page_allocator_;
    region_ = other.region_;
    other.Reset();
192 193 194
    return *this;
  }

195
  // Returns whether the memory has been reserved.
196
  bool IsReserved() const { return region_.begin() != kNullAddress; }
197 198

  // Initialize or resets an embedded VirtualMemory object.
199
  V8_EXPORT_PRIVATE void Reset();
200

201 202
  v8::PageAllocator* page_allocator() { return page_allocator_; }

203
  base::AddressRegion region() const { return region_; }
204

205 206 207 208
  // 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.
209
  Address address() const {
210
    DCHECK(IsReserved());
211
    return region_.begin();
212 213
  }

214
  Address end() const {
215
    DCHECK(IsReserved());
216
    return region_.end();
217 218 219 220 221 222
  }

  // 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.
223
  size_t size() const { return region_.size(); }
224

225 226
  // Sets permissions according to the access argument. address and size must be
  // multiples of CommitPageSize(). Returns true on success, otherwise false.
227 228
  V8_EXPORT_PRIVATE bool SetPermissions(Address address, size_t size,
                                        PageAllocator::Permission access);
229

230
  // Releases memory after |free_start|. Returns the number of bytes released.
231
  V8_EXPORT_PRIVATE size_t Release(Address free_start);
232

233
  // Frees all memory.
234
  V8_EXPORT_PRIVATE void Free();
235

236 237 238 239
  // 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();

240
  bool InVM(Address address, size_t size) {
241
    return region_.contains(address, size);
242 243 244
  }

 private:
245
  // Page allocator that controls the virtual memory.
246
  v8::PageAllocator* page_allocator_ = nullptr;
247
  base::AddressRegion region_;
248 249

  DISALLOW_COPY_AND_ASSIGN(VirtualMemory);
250 251
};

252 253
}  // namespace internal
}  // namespace v8
254

255
#endif  // V8_UTILS_ALLOCATION_H_