Coverage Report

Created: 2025-07-18 06:48

/src/dng_sdk/source/dng_safe_arithmetic.h
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *
3
 * Copyright (C) 2015 The Android Open Source Project
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
// Functions for safe arithmetic (guarded against overflow) on integer types.
19
20
#ifndef __dng_safe_arithmetic__
21
#define __dng_safe_arithmetic__
22
23
#include <climits>
24
#include <cstddef>
25
#include <cstdint>
26
#include <limits>
27
28
#include "dng_exceptions.h"
29
30
#ifndef __has_builtin
31
#define __has_builtin(x) 0  // Compatibility with non-Clang compilers.
32
#endif
33
34
#if !defined(DNG_HAS_INT128) && defined(__SIZEOF_INT128__)
35
#define DNG_HAS_INT128
36
#endif
37
38
// If the result of adding arg1 and arg2 will fit in an int32_t (without
39
// under-/overflow), stores this result in *result and returns true. Otherwise,
40
// returns false and leaves *result unchanged.
41
bool SafeInt32Add(std::int32_t arg1, std::int32_t arg2, std::int32_t *result);
42
43
// Returns the result of adding arg1 and arg2 if it will fit in the result type
44
// (without under-/overflow). Otherwise, throws a dng_exception with error code
45
// dng_error_unknown.
46
std::int32_t SafeInt32Add(std::int32_t arg1, std::int32_t arg2);
47
std::int64_t SafeInt64Add(std::int64_t arg1, std::int64_t arg2);
48
49
// If the result of adding arg1 and arg2 will fit in a uint32_t (without
50
// wraparound), stores this result in *result and returns true. Otherwise,
51
// returns false and leaves *result unchanged.
52
bool SafeUint32Add(std::uint32_t arg1, std::uint32_t arg2,
53
                   std::uint32_t *result);
54
55
// Returns the result of adding arg1 and arg2 if it will fit in the result type
56
// (without wraparound). Otherwise, throws a dng_exception with error code
57
// dng_error_unknown.
58
std::uint32_t SafeUint32Add(std::uint32_t arg1, std::uint32_t arg2);
59
std::uint64_t SafeUint64Add(std::uint64_t arg1, std::uint64_t arg2);
60
61
// If the subtraction of arg2 from arg1 will not result in an int32_t under- or
62
// overflow, stores this result in *result and returns true. Otherwise,
63
// returns false and leaves *result unchanged.
64
bool SafeInt32Sub(std::int32_t arg1, std::int32_t arg2, std::int32_t *result);
65
66
// Returns the result of subtracting arg2 from arg1 if this operation will not
67
// result in an int32_t under- or overflow. Otherwise, throws a dng_exception
68
// with error code dng_error_unknown.
69
std::int32_t SafeInt32Sub(std::int32_t arg1, std::int32_t arg2);
70
71
// Returns the result of subtracting arg2 from arg1 if this operation will not
72
// result in wraparound. Otherwise, throws a dng_exception with error code
73
// dng_error_unknown.
74
std::uint32_t SafeUint32Sub(std::uint32_t arg1, std::uint32_t arg2);
75
76
// Returns the result of multiplying arg1 and arg2 if it will fit in a int32_t
77
// (without overflow). Otherwise, throws a dng_exception with error code
78
// dng_error_unknown.
79
std::int32_t SafeInt32Mult(std::int32_t arg1, std::int32_t arg2);
80
81
// If the result of multiplying arg1, ..., argn will fit in a uint32_t (without
82
// wraparound), stores this result in *result and returns true. Otherwise,
83
// returns false and leaves *result unchanged.
84
bool SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2,
85
                    std::uint32_t *result);
86
bool SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2, std::uint32_t arg3,
87
                    std::uint32_t *result);
88
bool SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2, std::uint32_t arg3,
89
                    std::uint32_t arg4, std::uint32_t *result);
90
91
// Returns the result of multiplying arg1, ..., argn if it will fit in a
92
// uint32_t (without wraparound). Otherwise, throws a dng_exception with error
93
// code dng_error_unknown.
94
std::uint32_t SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2);
95
std::uint32_t SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2,
96
                             std::uint32_t arg3);
97
std::uint32_t SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2,
98
                             std::uint32_t arg3, std::uint32_t arg4);
99
100
// Returns the result of multiplying arg1 and arg2 if it will fit in a size_t
101
// (without overflow). Otherwise, throws a dng_exception with error code
102
// dng_error_unknown.
103
std::size_t SafeSizetMult(std::size_t arg1, std::size_t arg2);
104
105
namespace dng_internal {
106
107
// Internal function used as fallback for SafeInt64Mult() if other optimized
108
// computation is not supported. Don't call this function directly.
109
std::int64_t SafeInt64MultSlow(std::int64_t arg1, std::int64_t arg2);
110
111
// Internal function used as optimization for SafeInt64Mult() if Clang
112
// __builtin_smull_overflow is supported. Don't call this function directly.
113
#if __has_builtin(__builtin_smull_overflow)
114
1.66G
inline std::int64_t SafeInt64MultByClang(std::int64_t arg1, std::int64_t arg2) {
115
1.66G
  std::int64_t result;
116
1.66G
#if (LONG_MAX == INT64_MAX) && !defined(__APPLE__)
117
1.66G
  if (__builtin_smull_overflow(arg1, arg2, &result)) {
118
#else
119
  if (__builtin_smulll_overflow(arg1, arg2, &result)) {
120
#endif
121
0
    ThrowProgramError("Arithmetic overflow");
122
0
    abort();  // Never reached.
123
0
  }
124
1.66G
  return result;
125
1.66G
}
126
#endif
127
128
// Internal function used as optimization for SafeInt64Mult() if __int128 type
129
// is supported. Don't call this function directly.
130
#ifdef DNG_HAS_INT128
131
inline std::int64_t SafeInt64MultByInt128(std::int64_t arg1,
132
0
                                          std::int64_t arg2) {
133
0
  const __int128 kInt64Max =
134
0
      static_cast<__int128>(std::numeric_limits<std::int64_t>::max());
135
0
  const __int128 kInt64Min =
136
0
      static_cast<__int128>(std::numeric_limits<std::int64_t>::min());
137
0
  __int128 result = static_cast<__int128>(arg1) * static_cast<__int128>(arg2);
138
0
  if (result > kInt64Max || result < kInt64Min) {
139
0
    ThrowProgramError("Arithmetic overflow");
140
0
  }
141
0
  return static_cast<std::int64_t>(result);
142
0
}
143
#endif
144
145
}  // namespace dng_internal
146
147
// Returns the result of multiplying arg1 and arg2 if it will fit in an int64_t
148
// (without overflow). Otherwise, throws a dng_exception with error code
149
// dng_error_unknown.
150
1.66G
inline std::int64_t SafeInt64Mult(std::int64_t arg1, std::int64_t arg2) {
151
1.66G
#if __has_builtin(__builtin_smull_overflow)
152
1.66G
  return dng_internal::SafeInt64MultByClang(arg1, arg2);
153
#elif defined(DNG_HAS_INT128)
154
  return dng_internal::SafeInt64MultByInt128(arg1, arg2);
155
#else
156
  return dng_internal::SafeInt64MultSlow(arg1, arg2);
157
#endif
158
1.66G
}
159
160
// Returns the result of dividing arg1 by arg2; if the result is not an integer,
161
// rounds up to the next integer. If arg2 is zero, throws a dng_exception with
162
// error code dng_error_unknown.
163
// The function is safe against wraparound and will return the correct result
164
// for all combinations of arg1 and arg2.
165
std::uint32_t SafeUint32DivideUp(std::uint32_t arg1, std::uint32_t arg2);
166
167
// Finds the smallest integer multiple of 'multiple_of' that is greater than or
168
// equal to 'val'. If this value will fit in a uint32_t, stores it in *result
169
// and returns true. Otherwise, or if 'multiple_of' is zero, returns false and
170
// leaves *result unchanged.
171
bool RoundUpUint32ToMultiple(std::uint32_t val, std::uint32_t multiple_of,
172
                             std::uint32_t *result);
173
174
// Returns the smallest integer multiple of 'multiple_of' that is greater than
175
// or equal to 'val'. If the result will not fit in a std::uint32_t or if
176
// 'multiple_of' is zero, throws a dng_exception with error code
177
// dng_error_unknown.
178
std::uint32_t RoundUpUint32ToMultiple(std::uint32_t val,
179
                                      std::uint32_t multiple_of);
180
181
// If the uint32_t value val will fit in a int32_t, converts it to a int32_t and
182
// stores it in *result. Otherwise, returns false and leaves *result unchanged.
183
bool ConvertUint32ToInt32(std::uint32_t val, std::int32_t *result);
184
185
// Returns the result of converting val to an int32_t if it can be converted
186
// without overflow. Otherwise, throws a dng_exception with error code
187
// dng_error_unknown.
188
std::int32_t ConvertUint32ToInt32(std::uint32_t val);
189
190
// Converts a value of the unsigned integer type TSrc to the unsigned integer
191
// type TDest. If the value in 'src' cannot be converted to the type TDest
192
// without truncation, throws a dng_exception with error code dng_error_unknown.
193
//
194
// Note: Though this function is typically used where TDest is a narrower type
195
// than TSrc, it is designed to work also if TDest is wider than from TSrc or
196
// identical to TSrc. This is useful in situations where the width of the types
197
// involved can change depending on the architecture -- for example, the
198
// conversion from size_t to uint32_t may either be narrowing, identical or even
199
// widening (though the latter admittedly happens only on architectures that
200
// aren't relevant to us).
201
template <class TSrc, class TDest>
202
12.4M
static void ConvertUnsigned(TSrc src, TDest *dest) {
203
12.4M
  static_assert(std::numeric_limits<TSrc>::is_integer &&
204
12.4M
                    !std::numeric_limits<TSrc>::is_signed &&
205
12.4M
                    std::numeric_limits<TDest>::is_integer &&
206
12.4M
                    !std::numeric_limits<TDest>::is_signed,
207
12.4M
                "TSrc and TDest must be unsigned integer types");
208
209
12.4M
  const TDest converted = static_cast<TDest>(src);
210
211
  // Convert back to TSrc to check whether truncation occurred in the
212
  // conversion to TDest.
213
12.4M
  if (static_cast<TSrc>(converted) != src) {
214
0
    ThrowProgramError("Overflow in unsigned integer conversion");
215
0
  }
216
217
12.4M
  *dest = converted;
218
12.4M
}
dng_read_image.cpp:void ConvertUnsigned<unsigned int, unsigned long>(unsigned int, unsigned long*)
Line
Count
Source
202
86
static void ConvertUnsigned(TSrc src, TDest *dest) {
203
86
  static_assert(std::numeric_limits<TSrc>::is_integer &&
204
86
                    !std::numeric_limits<TSrc>::is_signed &&
205
86
                    std::numeric_limits<TDest>::is_integer &&
206
86
                    !std::numeric_limits<TDest>::is_signed,
207
86
                "TSrc and TDest must be unsigned integer types");
208
209
86
  const TDest converted = static_cast<TDest>(src);
210
211
  // Convert back to TSrc to check whether truncation occurred in the
212
  // conversion to TDest.
213
86
  if (static_cast<TSrc>(converted) != src) {
214
0
    ThrowProgramError("Overflow in unsigned integer conversion");
215
0
  }
216
217
86
  *dest = converted;
218
86
}
Unexecuted instantiation: dng_read_image.cpp:void ConvertUnsigned<unsigned int, unsigned int>(unsigned int, unsigned int*)
dng_string.cpp:void ConvertUnsigned<unsigned long, unsigned int>(unsigned long, unsigned int*)
Line
Count
Source
202
12.4M
static void ConvertUnsigned(TSrc src, TDest *dest) {
203
12.4M
  static_assert(std::numeric_limits<TSrc>::is_integer &&
204
12.4M
                    !std::numeric_limits<TSrc>::is_signed &&
205
12.4M
                    std::numeric_limits<TDest>::is_integer &&
206
12.4M
                    !std::numeric_limits<TDest>::is_signed,
207
12.4M
                "TSrc and TDest must be unsigned integer types");
208
209
12.4M
  const TDest converted = static_cast<TDest>(src);
210
211
  // Convert back to TSrc to check whether truncation occurred in the
212
  // conversion to TDest.
213
12.4M
  if (static_cast<TSrc>(converted) != src) {
214
0
    ThrowProgramError("Overflow in unsigned integer conversion");
215
0
  }
216
217
12.4M
  *dest = converted;
218
12.4M
}
dng_jpeg_memory_source.cpp:void ConvertUnsigned<unsigned long, unsigned long>(unsigned long, unsigned long*)
Line
Count
Source
202
20
static void ConvertUnsigned(TSrc src, TDest *dest) {
203
20
  static_assert(std::numeric_limits<TSrc>::is_integer &&
204
20
                    !std::numeric_limits<TSrc>::is_signed &&
205
20
                    std::numeric_limits<TDest>::is_integer &&
206
20
                    !std::numeric_limits<TDest>::is_signed,
207
20
                "TSrc and TDest must be unsigned integer types");
208
209
20
  const TDest converted = static_cast<TDest>(src);
210
211
  // Convert back to TSrc to check whether truncation occurred in the
212
  // conversion to TDest.
213
20
  if (static_cast<TSrc>(converted) != src) {
214
0
    ThrowProgramError("Overflow in unsigned integer conversion");
215
0
  }
216
217
20
  *dest = converted;
218
20
}
219
220
// Returns the result of converting val to the result type using truncation if
221
// val is in range of the result type values. Otherwise, throws a dng_exception
222
// with error code dng_error_unknown.
223
std::int32_t ConvertDoubleToInt32(double val);
224
std::uint32_t ConvertDoubleToUint32(double val);
225
226
// Returns the result of converting val to float. If val is outside of
227
// [-FLT_MAX, FLT_MAX], -infinity and infinity is returned respectively. NaN is
228
// returned as NaN.
229
float ConvertDoubleToFloat(double val);
230
231
#endif  // __dng_safe_arithmetic__