allocation.cc 1.88 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
#include "src/allocation.h"
6 7

#include <stdlib.h>  // For free, malloc.
8
#include "src/base/bits.h"
9 10
#include "src/base/logging.h"
#include "src/base/platform/platform.h"
11
#include "src/utils.h"
12
#include "src/v8.h"
13

14 15 16 17
#if V8_LIBC_BIONIC
#include <malloc.h>  // NOLINT
#endif

18 19
namespace v8 {
namespace internal {
20 21 22

void* Malloced::New(size_t size) {
  void* result = malloc(size);
23
  if (result == NULL) {
24
    V8::FatalProcessOutOfMemory("Malloced operator new");
25
  }
26 27 28 29 30 31 32 33 34 35
  return result;
}


void Malloced::Delete(void* p) {
  free(p);
}


char* StrDup(const char* str) {
36
  int length = StrLength(str);
37
  char* result = NewArray<char>(length + 1);
38
  MemCopy(result, str, length);
39 40 41 42 43
  result[length] = '\0';
  return result;
}


44 45
char* StrNDup(const char* str, int n) {
  int length = StrLength(str);
46 47
  if (n < length) length = n;
  char* result = NewArray<char>(length + 1);
48
  MemCopy(result, str, length);
49 50 51 52
  result[length] = '\0';
  return result;
}

53 54

void* AlignedAlloc(size_t size, size_t alignment) {
55
  DCHECK_LE(V8_ALIGNOF(void*), alignment);
56
  DCHECK(base::bits::IsPowerOfTwo64(alignment));
57 58 59 60 61 62 63 64 65 66
  void* ptr;
#if V8_OS_WIN
  ptr = _aligned_malloc(size, alignment);
#elif V8_LIBC_BIONIC
  // posix_memalign is not exposed in some Android versions, so we fall back to
  // memalign. See http://code.google.com/p/android/issues/detail?id=35391.
  ptr = memalign(alignment, size);
#else
  if (posix_memalign(&ptr, alignment, size)) ptr = NULL;
#endif
67
  if (ptr == NULL) V8::FatalProcessOutOfMemory("AlignedAlloc");
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  return ptr;
}


void AlignedFree(void *ptr) {
#if V8_OS_WIN
  _aligned_free(ptr);
#elif V8_LIBC_BIONIC
  // Using free is not correct in general, but for V8_LIBC_BIONIC it is.
  free(ptr);
#else
  free(ptr);
#endif
}

83 84
}  // namespace internal
}  // namespace v8