blob: 86dd23830869a8b7814e6aa62e6a29ea72925c76 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
[email protected]9f01b022012-07-26 02:22:392// 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
Avi Drissmanc73aa5d22023-12-07 17:24:227#include <bit>
8
Peter Boström54119652024-11-14 00:16:389#include "base/check.h"
Lei Zhang0d85a9d32021-05-06 19:21:4710#include "base/check_op.h"
[email protected]9f01b022012-07-26 02:22:3911#include "base/logging.h"
avi9beac252015-12-24 08:44:4712#include "build/build_config.h"
[email protected]9f01b022012-07-26 02:22:3913
Xiaohan Wang346275d2022-01-08 01:25:3714#if BUILDFLAG(IS_ANDROID)
[email protected]9f01b022012-07-26 02:22:3915#include <malloc.h>
16#endif
17
18namespace base {
19
20void* AlignedAlloc(size_t size, size_t alignment) {
21 DCHECK_GT(size, 0U);
Avi Drissmanc73aa5d22023-12-07 17:24:2222 DCHECK(std::has_single_bit(alignment));
[email protected]9f01b022012-07-26 02:22:3923 DCHECK_EQ(alignment % sizeof(void*), 0U);
Ivan Kotenkova16212a52017-11-08 12:37:3324 void* ptr = nullptr;
[email protected]9f01b022012-07-26 02:22:3925#if defined(COMPILER_MSVC)
26 ptr = _aligned_malloc(size, alignment);
Xiaohan Wang346275d2022-01-08 01:25:3727#elif BUILDFLAG(IS_ANDROID)
Lei Zhangd425ff92020-06-10 16:32:4228 // 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
[email protected]9f01b022012-07-26 02:22:3933 ptr = memalign(alignment, size);
34#else
Lei Zhangd425ff92020-06-10 16:32:4235 int ret = posix_memalign(&ptr, alignment, size);
36 if (ret != 0) {
Alexandre Courbot95a3cedc2019-01-23 05:08:4837 DLOG(ERROR) << "posix_memalign() returned with error " << ret;
Ivan Kotenkova16212a52017-11-08 12:37:3338 ptr = nullptr;
Alexandre Courbot95a3cedc2019-01-23 05:08:4839 }
[email protected]9f01b022012-07-26 02:22:3940#endif
Lei Zhangd425ff92020-06-10 16:32:4241
[email protected]9f01b022012-07-26 02:22:3942 // 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.
Peter Boström54119652024-11-14 00:16:3845 CHECK(ptr) << "If you crashed here, your aligned allocation is incorrect: "
46 << "size=" << size << ", alignment=" << alignment;
47
[email protected]9f01b022012-07-26 02:22:3948 // Sanity check alignment just to be safe.
Lei Zhangd425ff92020-06-10 16:32:4249 DCHECK(IsAligned(ptr, alignment));
[email protected]9f01b022012-07-26 02:22:3950 return ptr;
51}
52
53} // namespace base