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