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 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 30 void Malloced::Delete(void* p) { 31 free(p); 32 } 33 34 35 char* StrDup(const char* str) { 36 int length = StrLength(str); 37 char* result = NewArray<char>(length + 1); 38 MemCopy(result, str, length); 39 result[length] = '\0'; 40 return result; 41 } 42 43 44 char* StrNDup(const char* str, int n) { 45 int length = StrLength(str); 46 if (n < length) length = n; 47 char* result = NewArray<char>(length + 1); 48 MemCopy(result, str, length); 49 result[length] = '\0'; 50 return result; 51 } 52 53 54 void* AlignedAlloc(size_t size, size_t alignment) { 55 DCHECK_LE(V8_ALIGNOF(void*), alignment); 56 DCHECK(base::bits::IsPowerOfTwo64(alignment)); 57 void* ptr; 58 #if V8_OS_WIN 59 ptr = _aligned_malloc(size, alignment); 60 #elif V8_LIBC_BIONIC 61 // posix_memalign is not exposed in some Android versions, so we fall back to 62 // memalign. See http://code.google.com/p/android/issues/detail?id=35391. 63 ptr = memalign(alignment, size); 64 #else 65 if (posix_memalign(&ptr, alignment, size)) ptr = NULL; 66 #endif 67 if (ptr == NULL) V8::FatalProcessOutOfMemory("AlignedAlloc"); 68 return ptr; 69 } 70 71 72 void AlignedFree(void *ptr) { 73 #if V8_OS_WIN 74 _aligned_free(ptr); 75 #elif V8_LIBC_BIONIC 76 // Using free is not correct in general, but for V8_LIBC_BIONIC it is. 77 free(ptr); 78 #else 79 free(ptr); 80 #endif 81 } 82 83 } // namespace internal 84 } // namespace v8 85