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