summaryrefslogtreecommitdiff
path: root/source/dng_safe_arithmetic.cpp
blob: 577186114ba99b3c1f7cf89188d413311fc568cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#include "dng_safe_arithmetic.h"

#include <cmath>
#include <limits>

#include "dng_exceptions.h"

// Implementation of safe integer arithmetic follows guidelines from
// https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap
// and
// https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow

namespace {

// Template functions for safe arithmetic. These functions are not exposed in
// the header for the time being to avoid having to add checks for the various
// constraints on the template argument (e.g. that it is integral and possibly
// signed or unsigned only). This should be done using a static_assert(), but
// we want to be portable to pre-C++11 compilers.

// Returns the result of adding arg1 and arg2 if it will fit in a T (where T is
// a signed or unsigned integer type). Otherwise, throws a dng_exception with
// error code dng_error_unknown.
template <class T>
T SafeAdd(T arg1, T arg2) {
  // The condition is reformulated relative to the version on
  // www.securecoding.cert.org to check for valid instead of invalid cases. It
  // seems safer to enumerate the valid cases (and potentially miss one) than
  // enumerate the invalid cases.
  // If T is an unsigned type, the second half of the condition always evaluates
  // to false and will presumably be compiled out by the compiler.
  if ((arg1 >= 0 && arg2 <= std::numeric_limits<T>::max() - arg1) ||
      (arg1 < 0 && arg2 >= std::numeric_limits<T>::min() - arg1)) {
    return arg1 + arg2;
  } else {
    ThrowProgramError("Arithmetic overflow");
    abort();  // Never reached.
  }
}

// Returns the result of multiplying arg1 and arg2 if it will fit in a T (where
// T is an unsigned integer type). Otherwise, throws a dng_exception with error
// code dng_error_unknown.
template <class T>
T SafeUnsignedMult(T arg1, T arg2) {
  if (arg1 == 0 || arg2 <= std::numeric_limits<T>::max() / arg1) {
    return arg1 * arg2;
  } else {
    ThrowProgramError("Arithmetic overflow");
    abort();  // Never reached.
  }
}

}  // namespace

bool SafeInt32Add(std::int32_t arg1, std::int32_t arg2, std::int32_t *result) {
  try {
    *result = SafeInt32Add(arg1, arg2);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

std::int32_t SafeInt32Add(std::int32_t arg1, std::int32_t arg2) {
  return SafeAdd<std::int32_t>(arg1, arg2);
}

std::int64_t SafeInt64Add(std::int64_t arg1, std::int64_t arg2) {
  return SafeAdd<std::int64_t>(arg1, arg2);
}

bool SafeUint32Add(std::uint32_t arg1, std::uint32_t arg2,
                   std::uint32_t *result) {
  try {
    *result = SafeUint32Add(arg1, arg2);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

std::uint32_t SafeUint32Add(std::uint32_t arg1, std::uint32_t arg2) {
  return SafeAdd<std::uint32_t>(arg1, arg2);
}

std::uint64_t SafeUint64Add(std::uint64_t arg1, std::uint64_t arg2) {
  return SafeAdd<std::uint64_t>(arg1, arg2);
}

bool SafeInt32Sub(std::int32_t arg1, std::int32_t arg2, std::int32_t *result) {
  if ((arg2 >= 0 && arg1 >= std::numeric_limits<int32_t>::min() + arg2) ||
      (arg2 < 0 && arg1 <= std::numeric_limits<int32_t>::max() + arg2)) {
    *result = arg1 - arg2;
    return true;
  } else {
    return false;
  }
}

std::int32_t SafeInt32Sub(std::int32_t arg1, std::int32_t arg2) {
  std::int32_t result = 0;

  if (!SafeInt32Sub(arg1, arg2, &result)) {
    ThrowProgramError("Arithmetic overflow");
  }

  return result;
}

std::uint32_t SafeUint32Sub(std::uint32_t arg1, std::uint32_t arg2) {
  if (arg1 >= arg2) {
    return arg1 - arg2;
  } else {
    ThrowProgramError("Arithmetic overflow");
    abort();  // Never reached.
  }
}

bool SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2,
                    std::uint32_t *result) {
  try {
    *result = SafeUint32Mult(arg1, arg2);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

bool SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2, std::uint32_t arg3,
                    std::uint32_t *result) {
  try {
    *result = SafeUint32Mult(arg1, arg2, arg3);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

bool SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2, std::uint32_t arg3,
                    std::uint32_t arg4, std::uint32_t *result) {
  try {
    *result = SafeUint32Mult(arg1, arg2, arg3, arg4);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

std::uint32_t SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2) {
  return SafeUnsignedMult<std::uint32_t>(arg1, arg2);
}

std::uint32_t SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2,
                             std::uint32_t arg3) {
  return SafeUint32Mult(SafeUint32Mult(arg1, arg2), arg3);
}

std::uint32_t SafeUint32Mult(std::uint32_t arg1, std::uint32_t arg2,
                             std::uint32_t arg3, std::uint32_t arg4) {
  return SafeUint32Mult(SafeUint32Mult(arg1, arg2, arg3), arg4);
}

std::int32_t SafeInt32Mult(std::int32_t arg1, std::int32_t arg2) {
  const std::int64_t tmp =
      static_cast<std::int64_t>(arg1) * static_cast<std::int64_t>(arg2);
  if (tmp >= std::numeric_limits<std::int32_t>::min() &&
      tmp <= std::numeric_limits<std::int32_t>::max()) {
    return static_cast<std::int32_t>(tmp);
  } else {
    ThrowProgramError("Arithmetic overflow");
    abort();
  }
}

std::size_t SafeSizetMult(std::size_t arg1, std::size_t arg2) {
  return SafeUnsignedMult<std::size_t>(arg1, arg2);
}

namespace dng_internal {

std::int64_t SafeInt64MultSlow(std::int64_t arg1, std::int64_t arg2) {
  bool overflow = true;

  if (arg1 > 0) {
    if (arg2 > 0) {
      overflow = (arg1 > std::numeric_limits<std::int64_t>::max() / arg2);
    } else {
      overflow = (arg2 < std::numeric_limits<std::int64_t>::min() / arg1);
    }
  } else {
    if (arg2 > 0) {
      overflow = (arg1 < std::numeric_limits<std::int64_t>::min() / arg2);
    } else {
      overflow = (arg1 != 0 &&
                  arg2 < std::numeric_limits<std::int64_t>::max() / arg1);
    }
  }

  if (overflow) {
    ThrowProgramError("Arithmetic overflow");
    abort();  // Never reached.
  } else {
    return arg1 * arg2;
  }
}

}  // namespace dng_internal

std::uint32_t SafeUint32DivideUp(std::uint32_t arg1, std::uint32_t arg2) {
  // It might seem more intuitive to implement this function simply as
  //
  //   return arg2 == 0 ? 0 : (arg1 + arg2 - 1) / arg2;
  //
  // but the expression "arg1 + arg2" can wrap around.

  if (arg2 == 0) {
    ThrowProgramError("Division by zero");
    abort();  // Never reached.
  } else if (arg1 == 0) {
    // If arg1 is zero, return zero to avoid wraparound in the expression
    //   "arg1 - 1" below.
    return 0;
  } else {
    return (arg1 - 1) / arg2 + 1;
  }
}

bool RoundUpUint32ToMultiple(std::uint32_t val, std::uint32_t multiple_of,
                             std::uint32_t *result) {
  try {
    *result = RoundUpUint32ToMultiple(val, multiple_of);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

std::uint32_t RoundUpUint32ToMultiple(std::uint32_t val,
                                      std::uint32_t multiple_of) {
  if (multiple_of == 0) {
    ThrowProgramError("multiple_of is zero in RoundUpUint32ToMultiple");
  }

  const std::uint32_t remainder = val % multiple_of;
  if (remainder == 0) {
    return val;
  } else {
    return SafeUint32Add(val, multiple_of - remainder);
  }
}

bool ConvertUint32ToInt32(std::uint32_t val, std::int32_t *result) {
  try {
    *result = ConvertUint32ToInt32(val);
    return true;
  } catch (const dng_exception &) {
    return false;
  }
}

std::int32_t ConvertUint32ToInt32(std::uint32_t val) {
  const std::uint32_t kInt32MaxAsUint32 =
      static_cast<std::uint32_t>(std::numeric_limits<std::int32_t>::max());

  if (val <= kInt32MaxAsUint32) {
    return static_cast<std::int32_t>(val);
  } else {
    ThrowProgramError("Arithmetic overflow");
    abort();  // Never reached.
  }
}

std::int32_t ConvertDoubleToInt32(double val) {
  const double kMin =
      static_cast<double>(std::numeric_limits<std::int32_t>::min());
  const double kMax =
      static_cast<double>(std::numeric_limits<std::int32_t>::max());
  // NaNs will fail this test; they always compare false.
  if (val > kMin - 1.0 && val < kMax + 1.0) {
    return static_cast<std::int32_t>(val);
  } else {
    ThrowProgramError("Argument not in range in ConvertDoubleToInt32");
    abort();  // Never reached.
  }
}

std::uint32_t ConvertDoubleToUint32(double val) {
  const double kMax =
      static_cast<double>(std::numeric_limits<std::uint32_t>::max());
  // NaNs will fail this test; they always compare false.
  if (val >= 0.0 && val < kMax + 1.0) {
    return static_cast<std::uint32_t>(val);
  } else {
    ThrowProgramError("Argument not in range in ConvertDoubleToUint32");
    abort();  // Never reached.
  }
}

float ConvertDoubleToFloat(double val) {
  const double kMax = std::numeric_limits<float>::max();
  if (val > kMax) {
    return std::numeric_limits<float>::infinity();
  } else if (val < -kMax) {
    return -std::numeric_limits<float>::infinity();
  } else {
    // The cases that end up here are:
    // - values in [-kMax, kMax]
    // - NaN (because it always compares false)
    return static_cast<float>(val);
  }
}