Botan 3.4.0
Crypto and TLS for C&
safeint.h
Go to the documentation of this file.
1/*
2* Safe(r) Integer Handling
3* (C) 2016 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#ifndef BOTAN_UTILS_SAFE_INT_H_
9#define BOTAN_UTILS_SAFE_INT_H_
10
11#include <botan/exceptn.h>
12#include <botan/internal/fmt.h>
13#include <optional>
14#include <string_view>
15
16#if defined(_MSC_VER)
17 #include <intsafe.h>
18#endif
19
20namespace Botan {
21
23 public:
24 Integer_Overflow_Detected(std::string_view file, int line) :
25 Exception(fmt("Integer overflow detected at {}:{}", file, line)) {}
26
27 ErrorType error_type() const noexcept override { return ErrorType::InternalError; }
28};
29
30inline size_t checked_add(size_t x, size_t y, const char* file, int line) {
31#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_add_overflow)
32 size_t z;
33 if(__builtin_add_overflow(x, y, &z)) [[unlikely]]
34#elif defined(_MSC_VER)
35 size_t z;
36 if(SizeTAdd(x, y, &z) != S_OK) [[unlikely]]
37#else
38 size_t z = x + y;
39 if(z < x) [[unlikely]]
40#endif
41 {
42 throw Integer_Overflow_Detected(file, line);
43 }
44 return z;
45}
46
47inline std::optional<size_t> checked_mul(size_t x, size_t y) {
48#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_add_overflow)
49 size_t z;
50 if(__builtin_mul_overflow(x, y, &z)) [[unlikely]]
51#elif defined(_MSC_VER)
52 size_t z;
53 if(SizeTMult(x, y, &z) != S_OK) [[unlikely]]
54#else
55 size_t z = x * y;
56 if(y && z / y != x) [[unlikely]]
57#endif
58 {
59 return std::nullopt;
60 }
61 return z;
62}
63
64template <typename RT, typename AT>
66 RT c = static_cast<RT>(i);
67 if(i != static_cast<AT>(c)) {
68 throw Internal_Error("Error during integer conversion");
69 }
70 return c;
71}
72
73#define BOTAN_CHECKED_ADD(x, y) checked_add(x, y, __FILE__, __LINE__)
74#define BOTAN_CHECKED_MUL(x, y) checked_mul(x, y)
75
76} // namespace Botan
77
78#endif
Integer_Overflow_Detected(std::string_view file, int line)
Definition safeint.h:24
ErrorType error_type() const noexcept override
Definition safeint.h:27
int(* final)(unsigned char *, CTX *)
std::optional< size_t > checked_mul(size_t x, size_t y)
Definition safeint.h:47
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
ErrorType
Definition exceptn.h:20
size_t checked_add(size_t x, size_t y, const char *file, int line)
Definition safeint.h:30
RT checked_cast_to(AT i)
Definition safeint.h:65