Botan 3.0.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 {
24 public:
25 Integer_Overflow_Detected(std::string_view file, int line) :
26 Exception(fmt("Integer overflow detected at {}:{}", file, line))
27 {}
28
29 ErrorType error_type() const noexcept override { return ErrorType::InternalError; }
30 };
31
32inline size_t checked_add(size_t x, size_t y, const char* file, int line)
33 {
34#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_add_overflow)
35 size_t z;
36 if(__builtin_add_overflow(x, y, &z)) [[unlikely]]
37#elif defined(_MSC_VER)
38 size_t z;
39 if(SizeTAdd(x, y, &z) != S_OK) [[unlikely]]
40#else
41 size_t z = x + y;
42 if(z < x) [[unlikely]]
43#endif
44 {
45 throw Integer_Overflow_Detected(file, line);
46 }
47 return z;
48 }
49
50inline std::optional<size_t> checked_mul(size_t x, size_t y)
51 {
52#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_add_overflow)
53 size_t z;
54 if(__builtin_mul_overflow(x, y, &z)) [[unlikely]]
55#elif defined(_MSC_VER)
56 size_t z;
57 if(SizeTMult(x, y, &z) != S_OK) [[unlikely]]
58#else
59 size_t z = x * y;
60 if(y && z / y != x) [[unlikely]]
61#endif
62 {
63 return std::nullopt;
64 }
65 return z;
66 }
67
68template<typename RT, typename AT>
70 {
71 RT c = static_cast<RT>(i);
72 if(i != static_cast<AT>(c))
73 throw Internal_Error("Error during integer conversion");
74 return c;
75 }
76
77#define BOTAN_CHECKED_ADD(x,y) checked_add(x,y,__FILE__,__LINE__)
78#define BOTAN_CHECKED_MUL(x,y) checked_mul(x,y)
79
80}
81
82#endif
static SIMD_4x64 y
Integer_Overflow_Detected(std::string_view file, int line)
Definition: safeint.h:25
ErrorType error_type() const noexcept override
Definition: safeint.h:29
int(* final)(unsigned char *, CTX *)
Definition: alg_id.cpp:12
std::optional< size_t > checked_mul(size_t x, size_t y)
Definition: safeint.h:50
std::string fmt(std::string_view format, const T &... args)
Definition: fmt.h:60
ErrorType
Definition: exceptn.h:20
size_t checked_add(size_t x, size_t y, const char *file, int line)
Definition: safeint.h:32
RT checked_cast_to(AT i)
Definition: safeint.h:69