blob: 326b942bbe718759b2f65b817302d96984acf40e [file] [log] [blame]
mtklein65e58242016-01-13 12:57:57 -08001/*
2 * Copyright 2016 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#include "Fuzz.h"
kjlubickdba57342016-01-21 05:03:28 -08009#include "SkCanvas.h"
10#include "SkCodec.h"
mtkleinf5e97822016-01-15 06:19:53 -080011#include "SkCommandLineFlags.h"
kjlubickdba57342016-01-21 05:03:28 -080012#include "SkData.h"
kjlubickdba57342016-01-21 05:03:28 -080013#include "SkImage.h"
14#include "SkImageEncoder.h"
15#include "SkMallocPixelRef.h"
16#include "SkPicture.h"
17#include "SkStream.h"
18
kjlubick5bd98a22016-02-18 06:27:38 -080019#include <cmath>
mtkleina1159422016-01-15 05:46:54 -080020#include <signal.h>
mtkleinf5e97822016-01-15 06:19:53 -080021#include <stdlib.h>
22
kjlubickdba57342016-01-21 05:03:28 -080023DEFINE_string2(bytes, b, "", "A path to a file. This can be the fuzz bytes or a binary to parse.");
mtkleind4387ea2016-01-21 06:13:52 -080024DEFINE_string2(name, n, "", "If --type is 'api', fuzz the API with this name.");
kjlubickdba57342016-01-21 05:03:28 -080025
kjlubick2a42f482016-02-16 16:14:23 -080026DEFINE_string2(type, t, "api", "How to interpret --bytes, either 'image_scale', 'image_mode', 'skp', or 'api'.");
27DEFINE_string2(dump, d, "", "If not empty, dump 'image*' or 'skp' types as a PNG with this name.");
kjlubickdba57342016-01-21 05:03:28 -080028
29static int printUsage(const char* name) {
mtkleind4387ea2016-01-21 06:13:52 -080030 SkDebugf("Usage: %s -t <type> -b <path/to/file> [-n api-to-fuzz]\n", name);
kjlubickdba57342016-01-21 05:03:28 -080031 return 1;
32}
kjlubick2a42f482016-02-16 16:14:23 -080033static uint8_t calculate_option(SkData*);
kjlubickdba57342016-01-21 05:03:28 -080034
35static int fuzz_api(SkData*);
kjlubick2a42f482016-02-16 16:14:23 -080036static int fuzz_img(SkData*, uint8_t, uint8_t);
kjlubickdba57342016-01-21 05:03:28 -080037static int fuzz_skp(SkData*);
mtklein65e58242016-01-13 12:57:57 -080038
39int main(int argc, char** argv) {
mtkleinf5e97822016-01-15 06:19:53 -080040 SkCommandLineFlags::Parse(argc, argv);
41
mtkleind0b82342016-01-15 07:56:20 -080042 const char* path = FLAGS_bytes.isEmpty() ? argv[0] : FLAGS_bytes[0];
43 SkAutoTUnref<SkData> bytes(SkData::NewFromFileName(path));
kjlubickdba57342016-01-21 05:03:28 -080044 if (!bytes) {
45 SkDebugf("Could not read %s\n", path);
46 return 2;
47 }
mtklein65e58242016-01-13 12:57:57 -080048
kjlubick2a42f482016-02-16 16:14:23 -080049 uint8_t option = calculate_option(bytes);
50
mtkleind4387ea2016-01-21 06:13:52 -080051 if (!FLAGS_type.isEmpty()) {
52 switch (FLAGS_type[0][0]) {
53 case 'a': return fuzz_api(bytes);
kjlubick2a42f482016-02-16 16:14:23 -080054
55 case 'i':
56 // We only allow one degree of freedom to avoid a search space explosion for afl-fuzz.
57 if (FLAGS_type[0][6] == 's') { // image_scale
58 return fuzz_img(bytes, option, 0);
59 }
60 // image_mode
61 return fuzz_img(bytes, 0, option);
mtkleind4387ea2016-01-21 06:13:52 -080062 case 's': return fuzz_skp(bytes);
63 }
kjlubickdba57342016-01-21 05:03:28 -080064 }
65 return printUsage(argv[0]);
66}
67
kjlubick2a42f482016-02-16 16:14:23 -080068// This adds up the first 1024 bytes and returns it as an 8 bit integer. This allows afl-fuzz to
69// deterministically excercise different paths, or *options* (such as different scaling sizes or
70// different image modes) without needing to introduce a parameter. This way we don't need a
71// image_scale1, image_scale2, image_scale4, etc fuzzer, we can just have a image_scale fuzzer.
72// Clients are expected to transform this number into a different range, e.g. with modulo (%).
73static uint8_t calculate_option(SkData* bytes) {
74 uint8_t total = 0;
75 const uint8_t* data = bytes->bytes();
76 for (size_t i = 0; i < 1024 && i < bytes->size(); i++) {
77 total += data[i];
78 }
79 return total;
80}
81
kjlubickdba57342016-01-21 05:03:28 -080082int fuzz_api(SkData* bytes) {
mtkleind4387ea2016-01-21 06:13:52 -080083 const char* name = FLAGS_name.isEmpty() ? "" : FLAGS_name[0];
84
mtklein65e58242016-01-13 12:57:57 -080085 for (auto r = SkTRegistry<Fuzzable>::Head(); r; r = r->next()) {
86 auto fuzzable = r->factory();
mtkleind4387ea2016-01-21 06:13:52 -080087 if (0 == strcmp(name, fuzzable.name)) {
mtkleinf5e97822016-01-15 06:19:53 -080088 SkDebugf("Fuzzing %s...\n", fuzzable.name);
89 Fuzz fuzz(bytes);
mtklein65e58242016-01-13 12:57:57 -080090 fuzzable.fn(&fuzz);
kjlubick47d158e2016-02-01 08:23:50 -080091 SkDebugf("[terminated] Success!\n");
kjlubickdba57342016-01-21 05:03:28 -080092 return 0;
mtklein65e58242016-01-13 12:57:57 -080093 }
94 }
mtkleind4387ea2016-01-21 06:13:52 -080095
96 SkDebugf("When using --type api, please choose an API to fuzz with --name/-n:\n");
97 for (auto r = SkTRegistry<Fuzzable>::Head(); r; r = r->next()) {
98 auto fuzzable = r->factory();
99 SkDebugf("\t%s\n", fuzzable.name);
100 }
kjlubickdba57342016-01-21 05:03:28 -0800101 return 1;
102}
103
104static void dump_png(SkBitmap bitmap) {
105 if (!FLAGS_dump.isEmpty()) {
106 SkImageEncoder::EncodeFile(FLAGS_dump[0], bitmap, SkImageEncoder::kPNG_Type, 100);
107 SkDebugf("Dumped to %s\n", FLAGS_dump[0]);
108 }
109}
110
kjlubick2a42f482016-02-16 16:14:23 -0800111int fuzz_img(SkData* bytes, uint8_t scale, uint8_t mode) {
112 // We can scale 1x, 2x, 4x, 8x, 16x
113 scale = scale % 5;
kjlubick5bd98a22016-02-18 06:27:38 -0800114 float fscale = (float)pow(2.0f, scale);
115 SkDebugf("Scaling factor: %f\n", fscale);
kjlubick2a42f482016-02-16 16:14:23 -0800116
117 // We have 4 different modes of decoding, just like DM.
118 mode = mode % 4;
119 SkDebugf("Mode: %d\n", mode);
120
121 // This is mostly copied from DMSrcSink's CodecSrc::draw method.
kjlubick47d158e2016-02-01 08:23:50 -0800122 SkDebugf("Decoding\n");
kjlubickdba57342016-01-21 05:03:28 -0800123 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(bytes));
124 if (nullptr == codec.get()) {
kjlubick47d158e2016-02-01 08:23:50 -0800125 SkDebugf("[terminated] Couldn't create codec.\n");
kjlubickdba57342016-01-21 05:03:28 -0800126 return 3;
127 }
128
129 SkImageInfo decodeInfo = codec->getInfo();
kjlubick2a42f482016-02-16 16:14:23 -0800130
131 SkISize size = codec->getScaledDimensions(fscale);
132 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
133
kjlubickdba57342016-01-21 05:03:28 -0800134 // Construct a color table for the decode if necessary
135 SkAutoTUnref<SkColorTable> colorTable(nullptr);
136 SkPMColor* colorPtr = nullptr;
137 int* colorCountPtr = nullptr;
138 int maxColors = 256;
139 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
140 SkPMColor colors[256];
141 colorTable.reset(new SkColorTable(colors, maxColors));
142 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
143 colorCountPtr = &maxColors;
144 }
145
146 SkBitmap bitmap;
147 SkMallocPixelRef::ZeroedPRFactory zeroFactory;
148 SkCodec::Options options;
149 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
150
kjlubick2a42f482016-02-16 16:14:23 -0800151 if (!bitmap.tryAllocPixels(decodeInfo, &zeroFactory, colorTable.get())) {
kjlubick47d158e2016-02-01 08:23:50 -0800152 SkDebugf("[terminated] Could not allocate memory. Image might be too large (%d x %d)",
kjlubick2a42f482016-02-16 16:14:23 -0800153 decodeInfo.width(), decodeInfo.height());
kjlubickdba57342016-01-21 05:03:28 -0800154 return 4;
155 }
156
kjlubick2a42f482016-02-16 16:14:23 -0800157 switch (mode) {
158 case 0: {//kCodecZeroInit_Mode, kCodec_Mode
159 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), &options,
160 colorPtr, colorCountPtr)) {
161 case SkCodec::kSuccess:
162 SkDebugf("[terminated] Success!\n");
163 break;
164 case SkCodec::kIncompleteInput:
165 SkDebugf("[terminated] Partial Success\n");
166 break;
167 case SkCodec::kInvalidConversion:
168 SkDebugf("Incompatible colortype conversion\n");
169 // Crash to allow afl-fuzz to know this was a bug.
170 raise(SIGSEGV);
171 default:
172 SkDebugf("[terminated] Couldn't getPixels.\n");
173 return 6;
174 }
175 break;
176 }
177 case 1: {//kScanline_Mode
178 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
179 colorCountPtr)) {
180 SkDebugf("[terminated] Could not start scanline decoder\n");
181 return 7;
182 }
183
184 void* dst = bitmap.getAddr(0, 0);
185 size_t rowBytes = bitmap.rowBytes();
186 uint32_t height = decodeInfo.height();
187 switch (codec->getScanlineOrder()) {
188 case SkCodec::kTopDown_SkScanlineOrder:
189 case SkCodec::kBottomUp_SkScanlineOrder:
190 case SkCodec::kNone_SkScanlineOrder:
191 // We do not need to check the return value. On an incomplete
192 // image, memory will be filled with a default value.
193 codec->getScanlines(dst, height, rowBytes);
194 break;
195 case SkCodec::kOutOfOrder_SkScanlineOrder: {
196 for (int y = 0; y < decodeInfo.height(); y++) {
197 int dstY = codec->outputScanline(y);
198 void* dstPtr = bitmap.getAddr(0, dstY);
199 // We complete the loop, even if this call begins to fail
200 // due to an incomplete image. This ensures any uninitialized
201 // memory will be filled with the proper value.
202 codec->getScanlines(dstPtr, 1, bitmap.rowBytes());
203 }
204 break;
205 }
206 }
kjlubick47d158e2016-02-01 08:23:50 -0800207 SkDebugf("[terminated] Success!\n");
kjlubickdba57342016-01-21 05:03:28 -0800208 break;
kjlubick2a42f482016-02-16 16:14:23 -0800209 }
210 case 2: { //kStripe_Mode
211 const int height = decodeInfo.height();
212 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
213 // does not align with image blocks.
214 const int stripeHeight = 37;
215 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
216
217 // Decode odd stripes
218 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
219 colorCountPtr)
220 || SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
221 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
222 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
223 // to run this test for image types that do not have this scanline ordering.
224 SkDebugf("[terminated] Could not start top-down scanline decoder\n");
225 return 8;
226 }
227
228 for (int i = 0; i < numStripes; i += 2) {
229 // Skip a stripe
230 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
231 codec->skipScanlines(linesToSkip);
232
233 // Read a stripe
234 const int startY = (i + 1) * stripeHeight;
235 const int linesToRead = SkTMin(stripeHeight, height - startY);
236 if (linesToRead > 0) {
237 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
238 }
239 }
240
241 // Decode even stripes
242 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo, nullptr,
243 colorPtr, colorCountPtr);
244 if (SkCodec::kSuccess != startResult) {
245 SkDebugf("[terminated] Failed to restart scanline decoder with same parameters.\n");
246 return 9;
247 }
248 for (int i = 0; i < numStripes; i += 2) {
249 // Read a stripe
250 const int startY = i * stripeHeight;
251 const int linesToRead = SkTMin(stripeHeight, height - startY);
252 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
253
254 // Skip a stripe
255 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
256 if (linesToSkip > 0) {
257 codec->skipScanlines(linesToSkip);
258 }
259 }
260 SkDebugf("[terminated] Success!\n");
kjlubickdba57342016-01-21 05:03:28 -0800261 break;
kjlubick2a42f482016-02-16 16:14:23 -0800262 }
263 case 3: { //kSubset_Mode
264 // Arbitrarily choose a divisor.
265 int divisor = 2;
266 // Total width/height of the image.
267 const int W = codec->getInfo().width();
268 const int H = codec->getInfo().height();
269 if (divisor > W || divisor > H) {
270 SkDebugf("[terminated] Cannot codec subset: divisor %d is too big "
271 "with dimensions (%d x %d)\n", divisor, W, H);
272 return 10;
273 }
274 // subset dimensions
275 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
276 const int w = SkAlign2(W / divisor);
277 const int h = SkAlign2(H / divisor);
278 SkIRect subset;
279 SkCodec::Options opts;
280 opts.fSubset = &subset;
281 SkBitmap subsetBm;
282 // We will reuse pixel memory from bitmap.
283 void* pixels = bitmap.getPixels();
284 // Keep track of left and top (for drawing subsetBm into canvas). We could use
285 // fscale * x and fscale * y, but we want integers such that the next subset will start
286 // where the last one ended. So we'll add decodeInfo.width() and height().
287 int left = 0;
288 for (int x = 0; x < W; x += w) {
289 int top = 0;
290 for (int y = 0; y < H; y+= h) {
291 // Do not make the subset go off the edge of the image.
292 const int preScaleW = SkTMin(w, W - x);
293 const int preScaleH = SkTMin(h, H - y);
294 subset.setXYWH(x, y, preScaleW, preScaleH);
295 // And fscale
296 // FIXME: Should we have a version of getScaledDimensions that takes a subset
297 // into account?
298 decodeInfo = decodeInfo.makeWH(
299 SkTMax(1, SkScalarRoundToInt(preScaleW * fscale)),
300 SkTMax(1, SkScalarRoundToInt(preScaleH * fscale)));
301 size_t rowBytes = decodeInfo.minRowBytes();
302 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
303 nullptr, nullptr)) {
304 SkDebugf("[terminated] Could not install pixels.\n");
305 return 11;
306 }
307 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
308 &opts, colorPtr, colorCountPtr);
309 switch (result) {
310 case SkCodec::kSuccess:
311 case SkCodec::kIncompleteInput:
312 SkDebugf("okay\n");
313 break;
314 case SkCodec::kInvalidConversion:
315 if (0 == (x|y)) {
316 // First subset is okay to return unimplemented.
317 SkDebugf("[terminated] Incompatible colortype conversion\n");
318 return 12;
319 }
320 // If the first subset succeeded, a later one should not fail.
321 // fall through to failure
322 case SkCodec::kUnimplemented:
323 if (0 == (x|y)) {
324 // First subset is okay to return unimplemented.
325 SkDebugf("[terminated] subset codec not supported\n");
326 return 13;
327 }
328 // If the first subset succeeded, why would a later one fail?
329 // fall through to failure
330 default:
331 SkDebugf("[terminated] subset codec failed to decode (%d, %d, %d, %d) "
332 "with dimensions (%d x %d)\t error %d\n",
333 x, y, decodeInfo.width(), decodeInfo.height(),
334 W, H, result);
335 return 14;
336 }
337 // translate by the scaled height.
338 top += decodeInfo.height();
339 }
340 // translate by the scaled width.
341 left += decodeInfo.width();
342 }
343 SkDebugf("[terminated] Success!\n");
344 break;
345 }
kjlubickdba57342016-01-21 05:03:28 -0800346 default:
kjlubick2a42f482016-02-16 16:14:23 -0800347 SkDebugf("[terminated] Mode not implemented yet\n");
kjlubickdba57342016-01-21 05:03:28 -0800348 }
349
350 dump_png(bitmap);
mtkleinf5e97822016-01-15 06:19:53 -0800351 return 0;
mtklein65e58242016-01-13 12:57:57 -0800352}
353
kjlubickdba57342016-01-21 05:03:28 -0800354int fuzz_skp(SkData* bytes) {
355 SkMemoryStream stream(bytes);
356 SkDebugf("Decoding\n");
reedca2622b2016-03-18 07:25:55 -0700357 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(&stream));
kjlubickdba57342016-01-21 05:03:28 -0800358 if (!pic) {
kjlubick47d158e2016-02-01 08:23:50 -0800359 SkDebugf("[terminated] Couldn't decode as a picture.\n");
kjlubickdba57342016-01-21 05:03:28 -0800360 return 3;
361 }
362 SkDebugf("Rendering\n");
363 SkBitmap bitmap;
364 if (!FLAGS_dump.isEmpty()) {
365 SkIRect size = pic->cullRect().roundOut();
366 bitmap.allocN32Pixels(size.width(), size.height());
367 }
368 SkCanvas canvas(bitmap);
369 canvas.drawPicture(pic);
kjlubick47d158e2016-02-01 08:23:50 -0800370 SkDebugf("[terminated] Success! Decoded and rendered an SkPicture!\n");
kjlubickdba57342016-01-21 05:03:28 -0800371 dump_png(bitmap);
372 return 0;
373}
mtklein65e58242016-01-13 12:57:57 -0800374
mtklein24a22c72016-01-14 04:59:42 -0800375Fuzz::Fuzz(SkData* bytes) : fBytes(SkSafeRef(bytes)), fNextByte(0) {}
mtklein65e58242016-01-13 12:57:57 -0800376
kjlubick43195932016-04-05 12:48:47 -0700377void Fuzz::signalBug () { SkDebugf("Signal bug\n"); raise(SIGSEGV); }
378void Fuzz::signalBoring() { SkDebugf("Signal boring\n"); exit(0); }
mtkleina1159422016-01-15 05:46:54 -0800379
mtklein24a22c72016-01-14 04:59:42 -0800380template <typename T>
mtkleina1159422016-01-15 05:46:54 -0800381T Fuzz::nextT() {
382 if (fNextByte + sizeof(T) > fBytes->size()) {
383 this->signalBoring();
mtklein24a22c72016-01-14 04:59:42 -0800384 }
mtkleina1159422016-01-15 05:46:54 -0800385
mtklein24a22c72016-01-14 04:59:42 -0800386 T val;
mtkleina1159422016-01-15 05:46:54 -0800387 memcpy(&val, fBytes->bytes() + fNextByte, sizeof(T));
388 fNextByte += sizeof(T);
mtklein24a22c72016-01-14 04:59:42 -0800389 return val;
390}
391
mtkleina1159422016-01-15 05:46:54 -0800392uint8_t Fuzz::nextB() { return this->nextT<uint8_t >(); }
kjlubick5bd98a22016-02-18 06:27:38 -0800393bool Fuzz::nextBool() { return nextB()&1; }
mtkleina1159422016-01-15 05:46:54 -0800394uint32_t Fuzz::nextU() { return this->nextT<uint32_t>(); }
395float Fuzz::nextF() { return this->nextT<float >(); }
mtklein65e58242016-01-13 12:57:57 -0800396
kjlubick43195932016-04-05 12:48:47 -0700397float Fuzz::nextF1() {
398 // This is the same code as is in SkRandom's nextF()
399 unsigned int floatint = 0x3f800000 | (this->nextU() >> 9);
400 float f = SkBits2Float(floatint) - 1.0f;
401 return f;
402}
kjlubick5bd98a22016-02-18 06:27:38 -0800403
404uint32_t Fuzz::nextRangeU(uint32_t min, uint32_t max) {
405 if (min > max) {
406 SkDebugf("Check mins and maxes (%d, %d)\n", min, max);
407 this->signalBoring();
408 }
409 uint32_t range = max - min + 1;
410 if (0 == range) {
411 return this->nextU();
412 } else {
413 return min + this->nextU() % range;
414 }
415}
416float Fuzz::nextRangeF(float min, float max) {
417 if (min > max) {
418 SkDebugf("Check mins and maxes (%f, %f)\n", min, max);
419 this->signalBoring();
420 }
421 float f = std::abs(this->nextF());
422 if (!std::isnormal(f) && f != 0.0) {
423 this->signalBoring();
424 }
425 return min + fmod(f, (max - min + 1));
426}