93 lines · c
1//===-- Memory Size ---------------------------------------------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLVM_LIBC_SRC___SUPPORT_MEMORY_SIZE_H10#define LLVM_LIBC_SRC___SUPPORT_MEMORY_SIZE_H11 12#include "src/__support/CPP/bit.h" // has_single_bit13#include "src/__support/CPP/limits.h"14#include "src/__support/CPP/type_traits.h"15#include "src/__support/macros/attributes.h"16#include "src/__support/macros/config.h"17#include "src/__support/macros/optimization.h"18#include "src/string/memory_utils/utils.h"19 20namespace LIBC_NAMESPACE_DECL {21namespace internal {22template <class T> LIBC_INLINE bool mul_overflow(T a, T b, T *res) {23#if __has_builtin(__builtin_mul_overflow)24 return __builtin_mul_overflow(a, b, res);25#else26 T max = cpp::numeric_limits<T>::max();27 T min = cpp::numeric_limits<T>::min();28 bool overflow = (b > 0 && (a > max / b || a < min / b)) ||29 (b < 0 && (a < max / b || a > min / b));30 if (!overflow)31 *res = a * b;32 return overflow;33#endif34}35// Limit memory size to the max of ssize_t36class SafeMemSize {37private:38 using type = cpp::make_signed_t<size_t>;39 type value;40 LIBC_INLINE explicit SafeMemSize(type value) : value(value) {}41 42public:43 LIBC_INLINE_VAR static constexpr size_t MAX_MEM_SIZE =44 static_cast<size_t>(cpp::numeric_limits<type>::max());45 46 LIBC_INLINE explicit SafeMemSize(size_t value)47 : value(value <= MAX_MEM_SIZE ? static_cast<type>(value) : -1) {}48 49 LIBC_INLINE static constexpr size_t offset_to(size_t val, size_t align) {50 return (-val) & (align - 1);51 }52 53 LIBC_INLINE operator size_t() { return static_cast<size_t>(value); }54 55 LIBC_INLINE bool valid() { return value >= 0; }56 57 LIBC_INLINE SafeMemSize operator+(const SafeMemSize &other) {58 type result;59 if (LIBC_UNLIKELY((value | other.value) < 0)) {60 result = -1;61 } else {62 result = value + other.value;63 }64 return SafeMemSize{result};65 }66 67 LIBC_INLINE SafeMemSize operator*(const SafeMemSize &other) {68 type result;69 if (LIBC_UNLIKELY((value | other.value) < 0))70 result = -1;71 if (LIBC_UNLIKELY(mul_overflow(value, other.value, &result)))72 result = -1;73 return SafeMemSize{result};74 }75 76 LIBC_INLINE SafeMemSize align_up(size_t alignment) {77 if (!cpp::has_single_bit(alignment) || alignment > MAX_MEM_SIZE || !valid())78 return SafeMemSize{type{-1}};79 80 type offset =81 static_cast<type>(offset_to(static_cast<size_t>(value), alignment));82 83 if (LIBC_UNLIKELY(offset > static_cast<type>(MAX_MEM_SIZE) - value))84 return SafeMemSize{type{-1}};85 86 return SafeMemSize{value + offset};87 }88};89} // namespace internal90} // namespace LIBC_NAMESPACE_DECL91 92#endif // LLVM_LIBC_SRC___SUPPORT_MEMORY_SIZE_H93