aligned_memory.cc 1.7 KB

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