• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
AlignedAlloc(size_t size,size_t alignment)23 void *AlignedAlloc(size_t size, size_t alignment)
24 {
25     ASSERT(size > 0);
26     ASSERT((alignment & (alignment - 1)) == 0);
27     ASSERT((alignment % sizeof(void *)) == 0);
28     void *ptr = nullptr;
29 #if defined(ANGLE_PLATFORM_WINDOWS)
30     ptr = _aligned_malloc(size, alignment);
31 // Android technically supports posix_memalign(), but does not expose it in
32 // the current version of the library headers used by Chrome.  Luckily,
33 // memalign() on Android returns pointers which can safely be used with
34 // free(), so we can use it instead.  Issue filed to document this:
35 // http://code.google.com/p/android/issues/detail?id=35391
36 #elif defined(ANGLE_PLATFORM_ANDROID)
37     ptr = memalign(alignment, size);
38 #else
39     if (posix_memalign(&ptr, alignment, size))
40         ptr = nullptr;
41 #endif
42     // Since aligned allocations may fail for non-memory related reasons, force a
43     // crash if we encounter a failed allocation.
44     if (!ptr)
45     {
46         ERR() << "If you crashed here, your aligned allocation is incorrect: "
47               << "size=" << size << ", alignment=" << alignment;
48         ASSERT(false);
49     }
50     // Confidence check alignment just to be safe.
51     ASSERT((reinterpret_cast<uintptr_t>(ptr) & (alignment - 1)) == 0);
52     return ptr;
53 }
54 
AlignedFree(void * ptr)55 void AlignedFree(void *ptr)
56 {
57 #if defined(ANGLE_PLATFORM_WINDOWS)
58     _aligned_free(ptr);
59 #else
60     free(ptr);
61 #endif
62 }
63 
64 }  // namespace angle
65