• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 "third_party/base/memory/aligned_memory.h"
6 
7 #include "build/build_config.h"
8 #include "third_party/base/check_op.h"
9 
10 #if BUILDFLAG(IS_ANDROID)
11 #include <malloc.h>
12 #endif
13 
14 namespace pdfium {
15 namespace base {
16 
AlignedAlloc(size_t size,size_t alignment)17 void* AlignedAlloc(size_t size, size_t alignment) {
18   DCHECK(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 Chrome.  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     ptr = nullptr;
35   }
36 #endif
37 
38   // Since aligned allocations may fail for non-memory related reasons, force a
39   // crash if we encounter a failed allocation; maintaining consistent behavior
40   // with a normal allocation failure in Chrome.
41   if (!ptr) {
42     CHECK(false);
43   }
44   // Sanity check alignment just to be safe.
45   DCHECK(IsAligned(ptr, alignment));
46   return ptr;
47 }
48 
49 }  // namespace base
50 }  // namespace pdfium
51