| 1 |
/* |
| 2 |
* Copyright 2023 Google LLC |
| 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 |
#include "src/core/SkWritePixelsRec.h" |
| 9 |
|
| 10 |
#include "include/core/SkRect.h" |
| •11 |
#include "src/base/SkSafeMath.h" |
| 12 |
|
| 13 |
bool SkWritePixelsRec::trim(int dstWidth, int dstHeight) { |
| •14 |
// fInfo.minRowBytes() returns 0 if the size doesn't fit in `size_t`. |
| 15 |
const size_t minRowBytes = fInfo.minRowBytes(); |
| 16 |
if (nullptr == fPixels || fRowBytes < minRowBytes || minRowBytes == 0) { |
| 17 |
return false; |
| 18 |
} |
| 19 |
if (0 >= fInfo.width() || 0 >= fInfo.height()) { |
| 20 |
return false; |
| 21 |
} |
| 22 |
|
| 23 |
int x = fX; |
| 24 |
int y = fY; |
| 25 |
SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height()); |
| 26 |
if (!dstR.intersect({0, 0, dstWidth, dstHeight})) { |
| 27 |
return false; |
| 28 |
} |
| 29 |
|
| 30 |
// if x or y are negative, then we have to adjust pixels |
| 31 |
if (x > 0) { |
| 32 |
x = 0; |
| 33 |
} |
| 34 |
if (y > 0) { |
| 35 |
y = 0; |
| 36 |
} |
| •37 |
// here x,y are either 0 or negative (safe to cast to size_t) |
| 38 |
// we negate and add them so UBSAN (pointer-overflow) doesn't get confused. |
| •39 |
SkSafeMath safeMath; |
| 40 |
const size_t y_offset = safeMath.mul(-y, fRowBytes); |
| 41 |
const size_t x_offset = safeMath.mul(-x, fInfo.bytesPerPixel()); |
| 42 |
const size_t total = safeMath.add(y_offset, x_offset); |
| 43 |
if (!safeMath.ok()) { |
| 44 |
return false; |
| 45 |
} |
| 46 |
|
| 47 |
fPixels = ((const char*)fPixels + total); |
| 48 |
// the intersect may have shrunk info's logical size |
| 49 |
fInfo = fInfo.makeDimensions(dstR.size()); |
| 50 |
fX = dstR.x(); |
| 51 |
fY = dstR.y(); |
| 52 |
|
| 53 |
return true; |
| 54 |
} |