• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
operator new(size_t size)50 void* AllStatic::operator new(size_t size) {
51   UNREACHABLE();
52   return invalid;
53 }
54 
55 
operator delete(void * p)56 void AllStatic::operator delete(void* p) {
57   UNREACHABLE();
58 }
59 
60 #endif
61 
62 
StrDup(const char * str)63 char* StrDup(const char* str) {
64   int length = StrLength(str);
65   char* result = NewArray<char>(length + 1);
66   MemCopy(result, str, length);
67   result[length] = '\0';
68   return result;
69 }
70 
71 
StrNDup(const char * str,int n)72 char* StrNDup(const char* str, int n) {
73   int length = StrLength(str);
74   if (n < length) length = n;
75   char* result = NewArray<char>(length + 1);
76   MemCopy(result, str, length);
77   result[length] = '\0';
78   return result;
79 }
80 
81 
AlignedAlloc(size_t size,size_t alignment)82 void* AlignedAlloc(size_t size, size_t alignment) {
83   DCHECK_LE(V8_ALIGNOF(void*), alignment);
84   DCHECK(base::bits::IsPowerOfTwo64(alignment));
85   void* ptr;
86 #if V8_OS_WIN
87   ptr = _aligned_malloc(size, alignment);
88 #elif V8_LIBC_BIONIC
89   // posix_memalign is not exposed in some Android versions, so we fall back to
90   // memalign. See http://code.google.com/p/android/issues/detail?id=35391.
91   ptr = memalign(alignment, size);
92 #else
93   if (posix_memalign(&ptr, alignment, size)) ptr = NULL;
94 #endif
95   if (ptr == NULL) V8::FatalProcessOutOfMemory("AlignedAlloc");
96   return ptr;
97 }
98 
99 
AlignedFree(void * ptr)100 void AlignedFree(void *ptr) {
101 #if V8_OS_WIN
102   _aligned_free(ptr);
103 #elif V8_LIBC_BIONIC
104   // Using free is not correct in general, but for V8_LIBC_BIONIC it is.
105   free(ptr);
106 #else
107   free(ptr);
108 #endif
109 }
110 
111 }  // namespace internal
112 }  // namespace v8
113