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