1 // Copyright 2012 The Chromium Authors
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 "base/memory/aligned_memory.h"
6
7 #include "base/check_op.h"
8 #include "base/logging.h"
9 #include "build/build_config.h"
10
11 #if BUILDFLAG(IS_ANDROID)
12 #include <malloc.h>
13 #endif
14
15 namespace base {
16
AlignedAlloc(size_t size,size_t alignment)17 void* AlignedAlloc(size_t size, size_t alignment) {
18 DCHECK_GT(size, 0U);
19 DCHECK(bits::IsPowerOfTwo(alignment));
20 DCHECK_EQ(alignment % sizeof(void*), 0U);
21 void* ptr = nullptr;
22 #if defined(COMPILER_MSVC)
23 ptr = _aligned_malloc(size, alignment);
24 #elif BUILDFLAG(IS_ANDROID)
25 // Android technically supports posix_memalign(), but does not expose it in
26 // the current version of the library headers used by Chromium. Luckily,
27 // memalign() on Android returns pointers which can safely be used with
28 // free(), so we can use it instead. Issue filed to document this:
29 // http://code.google.com/p/android/issues/detail?id=35391
30 ptr = memalign(alignment, size);
31 #else
32 int ret = posix_memalign(&ptr, alignment, size);
33 if (ret != 0) {
34 DLOG(ERROR) << "posix_memalign() returned with error " << ret;
35 ptr = nullptr;
36 }
37 #endif
38
39 // Since aligned allocations may fail for non-memory related reasons, force a
40 // crash if we encounter a failed allocation; maintaining consistent behavior
41 // with a normal allocation failure in Chrome.
42 if (!ptr) {
43 DLOG(ERROR) << "If you crashed here, your aligned allocation is incorrect: "
44 << "size=" << size << ", alignment=" << alignment;
45 CHECK(false);
46 }
47 // Sanity check alignment just to be safe.
48 DCHECK(IsAligned(ptr, alignment));
49 return ptr;
50 }
51
52 } // namespace base
53