1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef COMMON_COMPONENTS_HEAP_ALLOCATOR_ALLOC_UTILS_H
17 #define COMMON_COMPONENTS_HEAP_ALLOCATOR_ALLOC_UTILS_H
18
19 #include <cstdint>
20 #include <cstdio>
21
22 namespace common {
23 constexpr uint32_t ALLOC_UTIL_PAGE_SIZE = 4096;
24 #define ALLOCUTIL_PAGE_RND_UP(x) \
25 (((static_cast<uintptr_t>(x)) + ALLOC_UTIL_PAGE_SIZE - 1) & (~(ALLOC_UTIL_PAGE_SIZE - 1)))
26
27 template<typename T>
AllocUtilRndDown(T x,size_t n)28 constexpr T AllocUtilRndDown(T x, size_t n)
29 {
30 return (x & static_cast<size_t>(-n));
31 }
32
33 #ifdef _WIN64
34 #define ALLOCUTIL_MEM_UNMAP(address, sizeInBytes) \
35 if (!VirtualFree(reinterpret_cast<void*>(address), 0, MEM_RELEASE)) { \
36 LOG_COMMON(FATAL) << "VirtualFree failed. Process terminating."; \
37 UNREACHABLE_CC(); \
38 }
39 #else
40 #define ALLOCUTIL_MEM_UNMAP(address, sizeInBytes) \
41 if (munmap(reinterpret_cast<void*>(address), sizeInBytes) != EOK) { \
42 LOG_COMMON(FATAL) << "munmap failed. Process terminating."; \
43 UNREACHABLE_CC(); \
44 }
45 #endif
46
47 template<typename T>
AllocUtilRndUp(T x,size_t n)48 constexpr T AllocUtilRndUp(T x, size_t n)
49 {
50 return AllocUtilRndDown(x + n - 1, n);
51 }
52
53 } // namespace common
54
55 #endif // COMMON_COMPONENTS_HEAP_ALLOCATOR_ALLOC_UTILS_H
56