1 //
2 // Copyright 2017 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // aligned_memory: An aligned memory allocator. Based on Chrome's base/memory/aligned_memory.
7 //
8
9 #include "common/aligned_memory.h"
10
11 #include "common/debug.h"
12 #include "common/platform.h"
13
14 #if defined(COMPILER_MSVC)
15 # include <malloc.h>
16 #else
17 # include <stdlib.h>
18 #endif
19
20 namespace angle
21 {
22
23 // Note: this could rely on std::aligned_alloc() but it has caveats, see this note and bug:
24 // https://crsrc.org/c/base/memory/aligned_memory.h;drc=ae6a934f4a7cdedb3f5433ef9571d8be4b841f35;l=42
AlignedAlloc(size_t size,size_t alignment)25 void *AlignedAlloc(size_t size, size_t alignment)
26 {
27 ASSERT(size > 0);
28 ASSERT((alignment & (alignment - 1)) == 0);
29 ASSERT((alignment % sizeof(void *)) == 0);
30 void *ptr = nullptr;
31 #if defined(ANGLE_PLATFORM_WINDOWS)
32 ptr = _aligned_malloc(size, alignment);
33 // Android technically supports posix_memalign(), but does not expose it in
34 // the current version of the library headers used by Chrome. Luckily,
35 // memalign() on Android returns pointers which can safely be used with
36 // free(), so we can use it instead. Issue filed to document this:
37 // http://code.google.com/p/android/issues/detail?id=35391
38 #elif defined(ANGLE_PLATFORM_ANDROID)
39 ptr = memalign(alignment, size);
40 #else
41 if (posix_memalign(&ptr, alignment, size))
42 ptr = nullptr;
43 #endif
44 // Since aligned allocations may fail for non-memory related reasons, force a
45 // crash if we encounter a failed allocation.
46 if (!ptr)
47 {
48 ERR() << "If you crashed here, your aligned allocation is incorrect: " << "size=" << size
49 << ", alignment=" << alignment;
50 ASSERT(false);
51 }
52 // Confidence check alignment just to be safe.
53 ASSERT((reinterpret_cast<uintptr_t>(ptr) & (alignment - 1)) == 0);
54 return ptr;
55 }
56
AlignedFree(void * ptr)57 void AlignedFree(void *ptr)
58 {
59 #if defined(ANGLE_PLATFORM_WINDOWS)
60 _aligned_free(ptr);
61 #else
62 free(ptr);
63 #endif
64 }
65
66 } // namespace angle
67