1/* 2 * Copyright 2017 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8#ifndef SkSafeMath_DEFINED 9#define SkSafeMath_DEFINED 10 11// SkSafeMath always check that a series of operations do not overflow. 12// This must be correct for all platforms, because this is a check for safety at runtime. 13 14class SkSafeMath { 15public: 16 SkSafeMath() = default; 17 18 bool ok() const { return fOK; } 19 explicit operator bool() const { return fOK; } 20 21 size_t mul(size_t x, size_t y) { 22 return sizeof(size_t) == sizeof(uint64_t) ? mul64(x, y) : mul32(x, y); 23 } 24 25 size_t add(size_t x, size_t y) { 26 size_t result = x + y; 27 fOK &= result >= x; 28 return result; 29 } 30 31 /** 32 * Return a + b, unless this result is an overflow/underflow. In those cases, fOK will 33 * be set to false, and it is undefined what this returns. 34 */ 35 int addInt(int a, int b) { 36 if (b < 0 && a < std::numeric_limits<int>::min() - b) { 37 fOK = false; 38 return a; 39 } else if (b > 0 && a > std::numeric_limits<int>::max() - b) { 40 fOK = false; 41 return a; 42 } 43 return a + b; 44 } 45 46 size_t alignUp(size_t x, size_t alignment) { 47 SkASSERT(alignment && !(alignment & (alignment - 1))); 48 return add(x, alignment - 1) & ~(alignment - 1); 49 } 50 51 // These saturate to their results 52 static size_t Add(size_t x, size_t y); 53 static size_t Mul(size_t x, size_t y); 54 static size_t Align4(size_t x) { 55 SkSafeMath safe; 56 return safe.alignUp(x, 4); 57 } 58 59private: 60 uint32_t mul32(uint32_t x, uint32_t y) { 61 uint64_t bx = x; 62 uint64_t by = y; 63 uint64_t result = bx * by; 64 fOK &= result >> 32 == 0; 65 return result; 66 } 67 68 uint64_t mul64(uint64_t x, uint64_t y) { 69 if (x <= std::numeric_limits<uint64_t>::max() >> 32 70 && y <= std::numeric_limits<uint64_t>::max() >> 32) { 71 return x * y; 72 } else { 73 auto hi = [](uint64_t x) { return x >> 32; }; 74 auto lo = [](uint64_t x) { return x & 0xFFFFFFFF; }; 75 76 uint64_t lx_ly = lo(x) * lo(y); 77 uint64_t hx_ly = hi(x) * lo(y); 78 uint64_t lx_hy = lo(x) * hi(y); 79 uint64_t hx_hy = hi(x) * hi(y); 80 uint64_t result = 0; 81 result = this->add(lx_ly, (hx_ly << 32)); 82 result = this->add(result, (lx_hy << 32)); 83 fOK &= (hx_hy + (hx_ly >> 32) + (lx_hy >> 32)) == 0; 84 85 #if defined(SK_DEBUG) && defined(__clang__) && defined(__x86_64__) 86 auto double_check = (unsigned __int128)x * y; 87 SkASSERT(result == (double_check & 0xFFFFFFFFFFFFFFFF)); 88 SkASSERT(!fOK || (double_check >> 64 == 0)); 89 #endif 90 91 return result; 92 } 93 } 94 bool fOK = true; 95}; 96 97#endif//SkSafeMath_DEFINED 98