[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 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 "base/memory/aligned_memory.h" |
| 6 | |
| 7 | #include "base/logging.h" |
avi | 9beac25 | 2015-12-24 08:44:47 | [diff] [blame] | 8 | #include "build/build_config.h" |
[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 9 | |
[email protected] | 0a72447f | 2013-11-28 05:59:44 | [diff] [blame] | 10 | #if defined(OS_ANDROID) |
[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 11 | #include <malloc.h> |
| 12 | #endif |
| 13 | |
| 14 | namespace base { |
| 15 | |
| 16 | void* AlignedAlloc(size_t size, size_t alignment) { |
| 17 | DCHECK_GT(size, 0U); |
| 18 | DCHECK_EQ(alignment & (alignment - 1), 0U); |
| 19 | DCHECK_EQ(alignment % sizeof(void*), 0U); |
Ivan Kotenkov | a16212a5 | 2017-11-08 12:37:33 | [diff] [blame^] | 20 | void* ptr = nullptr; |
[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 21 | #if defined(COMPILER_MSVC) |
| 22 | ptr = _aligned_malloc(size, alignment); |
[email protected] | 0a72447f | 2013-11-28 05:59:44 | [diff] [blame] | 23 | // Android technically supports posix_memalign(), but does not expose it in |
| 24 | // the current version of the library headers used by Chrome. Luckily, |
| 25 | // memalign() on Android returns pointers which can safely be used with |
| 26 | // free(), so we can use it instead. Issue filed to document this: |
[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 27 | // http://code.google.com/p/android/issues/detail?id=35391 |
[email protected] | 0a72447f | 2013-11-28 05:59:44 | [diff] [blame] | 28 | #elif defined(OS_ANDROID) |
[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 29 | ptr = memalign(alignment, size); |
| 30 | #else |
| 31 | if (posix_memalign(&ptr, alignment, size)) |
Ivan Kotenkov | a16212a5 | 2017-11-08 12:37:33 | [diff] [blame^] | 32 | ptr = nullptr; |
[email protected] | 9f01b02 | 2012-07-26 02:22:39 | [diff] [blame] | 33 | #endif |
| 34 | // Since aligned allocations may fail for non-memory related reasons, force a |
| 35 | // crash if we encounter a failed allocation; maintaining consistent behavior |
| 36 | // with a normal allocation failure in Chrome. |
| 37 | if (!ptr) { |
| 38 | DLOG(ERROR) << "If you crashed here, your aligned allocation is incorrect: " |
| 39 | << "size=" << size << ", alignment=" << alignment; |
| 40 | CHECK(false); |
| 41 | } |
| 42 | // Sanity check alignment just to be safe. |
| 43 | DCHECK_EQ(reinterpret_cast<uintptr_t>(ptr) & (alignment - 1), 0U); |
| 44 | return ptr; |
| 45 | } |
| 46 | |
| 47 | } // namespace base |