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 #include "src/allocation.h"
6 
7 #include <stdlib.h>  // For free, malloc.
8 #include "src/base/bits.h"
9 #include "src/base/logging.h"
10 #include "src/base/platform/platform.h"
11 #include "src/utils.h"
12 #include "src/v8.h"
13 
14 #if V8_LIBC_BIONIC
15 #include <malloc.h>  // NOLINT
16 #endif
17 
18 namespace v8 {
19 namespace internal {
20 
New(size_t size)21 void* Malloced::New(size_t size) {
22   void* result = malloc(size);
23   if (result == NULL) {
24     V8::FatalProcessOutOfMemory("Malloced operator new");
25   }
26   return result;
27 }
28 
29 
Delete(void * p)30 void Malloced::Delete(void* p) {
31   free(p);
32 }
33 
34 
35 #ifdef DEBUG
36 
37 static void* invalid = static_cast<void*>(NULL);
38 
operator new(size_t size)39 void* Embedded::operator new(size_t size) {
40   UNREACHABLE();
41   return invalid;
42 }
43 
44 
operator delete(void * p)45 void Embedded::operator delete(void* p) {
46   UNREACHABLE();
47 }
48 
49 #endif
50 
51 
StrDup(const char * str)52 char* StrDup(const char* str) {
53   int length = StrLength(str);
54   char* result = NewArray<char>(length + 1);
55   MemCopy(result, str, length);
56   result[length] = '\0';
57   return result;
58 }
59 
60 
StrNDup(const char * str,int n)61 char* StrNDup(const char* str, int n) {
62   int length = StrLength(str);
63   if (n < length) length = n;
64   char* result = NewArray<char>(length + 1);
65   MemCopy(result, str, length);
66   result[length] = '\0';
67   return result;
68 }
69 
70 
AlignedAlloc(size_t size,size_t alignment)71 void* AlignedAlloc(size_t size, size_t alignment) {
72   DCHECK_LE(V8_ALIGNOF(void*), alignment);
73   DCHECK(base::bits::IsPowerOfTwo64(alignment));
74   void* ptr;
75 #if V8_OS_WIN
76   ptr = _aligned_malloc(size, alignment);
77 #elif V8_LIBC_BIONIC
78   // posix_memalign is not exposed in some Android versions, so we fall back to
79   // memalign. See http://code.google.com/p/android/issues/detail?id=35391.
80   ptr = memalign(alignment, size);
81 #else
82   if (posix_memalign(&ptr, alignment, size)) ptr = NULL;
83 #endif
84   if (ptr == NULL) V8::FatalProcessOutOfMemory("AlignedAlloc");
85   return ptr;
86 }
87 
88 
AlignedFree(void * ptr)89 void AlignedFree(void *ptr) {
90 #if V8_OS_WIN
91   _aligned_free(ptr);
92 #elif V8_LIBC_BIONIC
93   // Using free is not correct in general, but for V8_LIBC_BIONIC it is.
94   free(ptr);
95 #else
96   free(ptr);
97 #endif
98 }
99 
100 }  // namespace internal
101 }  // namespace v8
102