1 /*
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"
9 #include "SkCanvas.h"
10 #include "SkCodec.h"
11 #include "SkCommandLineFlags.h"
12 #include "SkData.h"
13 #include "SkFlattenableSerialization.h"
14 #include "SkImage.h"
15 #include "SkImageEncoder.h"
16 #include "SkImageFilter.h"
17 #include "SkMallocPixelRef.h"
18 #include "SkOSFile.h"
19 #include "SkOSPath.h"
20 #include "SkPaint.h"
21 #include "SkPath.h"
22 #include "SkPicture.h"
23 #include "SkRegion.h"
24 #include "SkStream.h"
25 #include "SkSurface.h"
26
27 #if SK_SUPPORT_GPU
28 #include "SkSLCompiler.h"
29 #endif
30
31 #include <iostream>
32 #include <signal.h>
33 #include "sk_tool_utils.h"
34
35
36 DEFINE_string2(bytes, b, "", "A path to a file or a directory. If a file, the "
37 "contents will be used as the fuzz bytes. If a directory, all files "
38 "in the directory will be used as fuzz bytes for the fuzzer, one at a "
39 "time.");
40 DEFINE_string2(name, n, "", "If --type is 'api', fuzz the API with this name.");
41
42 DEFINE_string2(type, t, "api", "How to interpret --bytes, either 'image_scale'"
43 ", 'image_mode', 'skp', 'icc', or 'api'.");
44 DEFINE_string2(dump, d, "", "If not empty, dump 'image*' or 'skp' types as a "
45 "PNG with this name.");
46
printUsage()47 static int printUsage() {
48 SkDebugf("Usage: fuzz -t <type> -b <path/to/file> [-n api-to-fuzz]\n");
49 return 1;
50 }
51 static int fuzz_file(const char* path);
52 static uint8_t calculate_option(SkData*);
53
54 static void fuzz_api(sk_sp<SkData>);
55 static void fuzz_color_deserialize(sk_sp<SkData>);
56 static void fuzz_icc(sk_sp<SkData>);
57 static void fuzz_img(sk_sp<SkData>, uint8_t, uint8_t);
58 static void fuzz_path_deserialize(sk_sp<SkData>);
59 static void fuzz_region_deserialize(sk_sp<SkData>);
60 static void fuzz_skp(sk_sp<SkData>);
61 static void fuzz_filter_fuzz(sk_sp<SkData>);
62
63 #if SK_SUPPORT_GPU
64 static void fuzz_sksl2glsl(sk_sp<SkData>);
65 #endif
66
main(int argc,char ** argv)67 int main(int argc, char** argv) {
68 SkCommandLineFlags::Parse(argc, argv);
69
70 const char* path = FLAGS_bytes.isEmpty() ? argv[0] : FLAGS_bytes[0];
71
72 if (!sk_isdir(path)) {
73 return fuzz_file(path);
74 }
75
76 SkOSFile::Iter it(path);
77 for (SkString file; it.next(&file); ) {
78 SkString p = SkOSPath::Join(path, file.c_str());
79 SkDebugf("Fuzzing %s\n", p.c_str());
80 int rv = fuzz_file(p.c_str());
81 if (rv != 0) {
82 return rv;
83 }
84 }
85 return 0;
86 }
87
fuzz_file(const char * path)88 static int fuzz_file(const char* path) {
89 sk_sp<SkData> bytes(SkData::MakeFromFileName(path));
90 if (!bytes) {
91 SkDebugf("Could not read %s\n", path);
92 return 1;
93 }
94
95 uint8_t option = calculate_option(bytes.get());
96
97 if (!FLAGS_type.isEmpty()) {
98 if (0 == strcmp("api", FLAGS_type[0])) {
99 fuzz_api(bytes);
100 return 0;
101 }
102 if (0 == strcmp("color_deserialize", FLAGS_type[0])) {
103 fuzz_color_deserialize(bytes);
104 return 0;
105 }
106 if (0 == strcmp("icc", FLAGS_type[0])) {
107 fuzz_icc(bytes);
108 return 0;
109 }
110 if (0 == strcmp("image_scale", FLAGS_type[0])) {
111 fuzz_img(bytes, option, 0);
112 return 0;
113 }
114 if (0 == strcmp("image_mode", FLAGS_type[0])) {
115 fuzz_img(bytes, 0, option);
116 return 0;
117 }
118 if (0 == strcmp("path_deserialize", FLAGS_type[0])) {
119 fuzz_path_deserialize(bytes);
120 return 0;
121 }
122 if (0 == strcmp("region_deserialize", FLAGS_type[0])) {
123 fuzz_region_deserialize(bytes);
124 return 0;
125 }
126 if (0 == strcmp("skp", FLAGS_type[0])) {
127 fuzz_skp(bytes);
128 return 0;
129 }
130 if (0 == strcmp("filter_fuzz", FLAGS_type[0])) {
131 fuzz_filter_fuzz(bytes);
132 return 0;
133 }
134 #if SK_SUPPORT_GPU
135 if (0 == strcmp("sksl2glsl", FLAGS_type[0])) {
136 fuzz_sksl2glsl(bytes);
137 return 0;
138 }
139 #endif
140 }
141 return printUsage();
142 }
143
144 // This adds up the first 1024 bytes and returns it as an 8 bit integer. This allows afl-fuzz to
145 // deterministically excercise different paths, or *options* (such as different scaling sizes or
146 // different image modes) without needing to introduce a parameter. This way we don't need a
147 // image_scale1, image_scale2, image_scale4, etc fuzzer, we can just have a image_scale fuzzer.
148 // Clients are expected to transform this number into a different range, e.g. with modulo (%).
calculate_option(SkData * bytes)149 static uint8_t calculate_option(SkData* bytes) {
150 uint8_t total = 0;
151 const uint8_t* data = bytes->bytes();
152 for (size_t i = 0; i < 1024 && i < bytes->size(); i++) {
153 total += data[i];
154 }
155 return total;
156 }
157
fuzz_api(sk_sp<SkData> bytes)158 static void fuzz_api(sk_sp<SkData> bytes) {
159 const char* name = FLAGS_name.isEmpty() ? "" : FLAGS_name[0];
160
161 for (auto r = sk_tools::Registry<Fuzzable>::Head(); r; r = r->next()) {
162 auto fuzzable = r->factory();
163 if (0 == strcmp(name, fuzzable.name)) {
164 SkDebugf("Fuzzing %s...\n", fuzzable.name);
165 Fuzz fuzz(std::move(bytes));
166 fuzzable.fn(&fuzz);
167 SkDebugf("[terminated] Success!\n");
168 return;
169 }
170 }
171
172 SkDebugf("When using --type api, please choose an API to fuzz with --name/-n:\n");
173 for (auto r = sk_tools::Registry<Fuzzable>::Head(); r; r = r->next()) {
174 auto fuzzable = r->factory();
175 SkDebugf("\t%s\n", fuzzable.name);
176 }
177 }
178
dump_png(SkBitmap bitmap)179 static void dump_png(SkBitmap bitmap) {
180 if (!FLAGS_dump.isEmpty()) {
181 sk_tool_utils::EncodeImageToFile(FLAGS_dump[0], bitmap, SkEncodedImageFormat::kPNG, 100);
182 SkDebugf("Dumped to %s\n", FLAGS_dump[0]);
183 }
184 }
185
fuzz_img(sk_sp<SkData> bytes,uint8_t scale,uint8_t mode)186 static void fuzz_img(sk_sp<SkData> bytes, uint8_t scale, uint8_t mode) {
187 // We can scale 1x, 2x, 4x, 8x, 16x
188 scale = scale % 5;
189 float fscale = (float)pow(2.0f, scale);
190 SkDebugf("Scaling factor: %f\n", fscale);
191
192 // We have 5 different modes of decoding.
193 mode = mode % 5;
194 SkDebugf("Mode: %d\n", mode);
195
196 // This is mostly copied from DMSrcSink's CodecSrc::draw method.
197 SkDebugf("Decoding\n");
198 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(bytes));
199 if (nullptr == codec.get()) {
200 SkDebugf("[terminated] Couldn't create codec.\n");
201 return;
202 }
203
204 SkImageInfo decodeInfo = codec->getInfo();
205 if (4 == mode && decodeInfo.colorType() == kIndex_8_SkColorType) {
206 // 4 means animated. Frames beyond the first cannot be decoded to
207 // index 8.
208 decodeInfo = decodeInfo.makeColorType(kN32_SkColorType);
209 }
210
211 SkISize size = codec->getScaledDimensions(fscale);
212 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
213
214 // Construct a color table for the decode if necessary
215 sk_sp<SkColorTable> colorTable(nullptr);
216 SkPMColor* colorPtr = nullptr;
217 int* colorCountPtr = nullptr;
218 int maxColors = 256;
219 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
220 SkPMColor colors[256];
221 colorTable.reset(new SkColorTable(colors, maxColors));
222 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
223 colorCountPtr = &maxColors;
224 }
225
226 SkBitmap bitmap;
227 SkMallocPixelRef::ZeroedPRFactory zeroFactory;
228 SkCodec::Options options;
229 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
230
231 if (!bitmap.tryAllocPixels(decodeInfo, &zeroFactory, colorTable.get())) {
232 SkDebugf("[terminated] Could not allocate memory. Image might be too large (%d x %d)",
233 decodeInfo.width(), decodeInfo.height());
234 return;
235 }
236
237 switch (mode) {
238 case 0: {//kCodecZeroInit_Mode, kCodec_Mode
239 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), &options,
240 colorPtr, colorCountPtr)) {
241 case SkCodec::kSuccess:
242 SkDebugf("[terminated] Success!\n");
243 break;
244 case SkCodec::kIncompleteInput:
245 SkDebugf("[terminated] Partial Success\n");
246 break;
247 case SkCodec::kInvalidConversion:
248 SkDebugf("Incompatible colortype conversion\n");
249 // Crash to allow afl-fuzz to know this was a bug.
250 raise(SIGSEGV);
251 default:
252 SkDebugf("[terminated] Couldn't getPixels.\n");
253 return;
254 }
255 break;
256 }
257 case 1: {//kScanline_Mode
258 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
259 colorCountPtr)) {
260 SkDebugf("[terminated] Could not start scanline decoder\n");
261 return;
262 }
263
264 void* dst = bitmap.getAddr(0, 0);
265 size_t rowBytes = bitmap.rowBytes();
266 uint32_t height = decodeInfo.height();
267 switch (codec->getScanlineOrder()) {
268 case SkCodec::kTopDown_SkScanlineOrder:
269 case SkCodec::kBottomUp_SkScanlineOrder:
270 // We do not need to check the return value. On an incomplete
271 // image, memory will be filled with a default value.
272 codec->getScanlines(dst, height, rowBytes);
273 break;
274 }
275 SkDebugf("[terminated] Success!\n");
276 break;
277 }
278 case 2: { //kStripe_Mode
279 const int height = decodeInfo.height();
280 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
281 // does not align with image blocks.
282 const int stripeHeight = 37;
283 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
284
285 // Decode odd stripes
286 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
287 colorCountPtr)
288 || SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
289 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
290 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
291 // to run this test for image types that do not have this scanline ordering.
292 SkDebugf("[terminated] Could not start top-down scanline decoder\n");
293 return;
294 }
295
296 for (int i = 0; i < numStripes; i += 2) {
297 // Skip a stripe
298 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
299 codec->skipScanlines(linesToSkip);
300
301 // Read a stripe
302 const int startY = (i + 1) * stripeHeight;
303 const int linesToRead = SkTMin(stripeHeight, height - startY);
304 if (linesToRead > 0) {
305 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
306 }
307 }
308
309 // Decode even stripes
310 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo, nullptr,
311 colorPtr, colorCountPtr);
312 if (SkCodec::kSuccess != startResult) {
313 SkDebugf("[terminated] Failed to restart scanline decoder with same parameters.\n");
314 return;
315 }
316 for (int i = 0; i < numStripes; i += 2) {
317 // Read a stripe
318 const int startY = i * stripeHeight;
319 const int linesToRead = SkTMin(stripeHeight, height - startY);
320 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
321
322 // Skip a stripe
323 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
324 if (linesToSkip > 0) {
325 codec->skipScanlines(linesToSkip);
326 }
327 }
328 SkDebugf("[terminated] Success!\n");
329 break;
330 }
331 case 3: { //kSubset_Mode
332 // Arbitrarily choose a divisor.
333 int divisor = 2;
334 // Total width/height of the image.
335 const int W = codec->getInfo().width();
336 const int H = codec->getInfo().height();
337 if (divisor > W || divisor > H) {
338 SkDebugf("[terminated] Cannot codec subset: divisor %d is too big "
339 "with dimensions (%d x %d)\n", divisor, W, H);
340 return;
341 }
342 // subset dimensions
343 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
344 const int w = SkAlign2(W / divisor);
345 const int h = SkAlign2(H / divisor);
346 SkIRect subset;
347 SkCodec::Options opts;
348 opts.fSubset = ⊂
349 SkBitmap subsetBm;
350 // We will reuse pixel memory from bitmap.
351 void* pixels = bitmap.getPixels();
352 // Keep track of left and top (for drawing subsetBm into canvas). We could use
353 // fscale * x and fscale * y, but we want integers such that the next subset will start
354 // where the last one ended. So we'll add decodeInfo.width() and height().
355 int left = 0;
356 for (int x = 0; x < W; x += w) {
357 int top = 0;
358 for (int y = 0; y < H; y+= h) {
359 // Do not make the subset go off the edge of the image.
360 const int preScaleW = SkTMin(w, W - x);
361 const int preScaleH = SkTMin(h, H - y);
362 subset.setXYWH(x, y, preScaleW, preScaleH);
363 // And fscale
364 // FIXME: Should we have a version of getScaledDimensions that takes a subset
365 // into account?
366 decodeInfo = decodeInfo.makeWH(
367 SkTMax(1, SkScalarRoundToInt(preScaleW * fscale)),
368 SkTMax(1, SkScalarRoundToInt(preScaleH * fscale)));
369 size_t rowBytes = decodeInfo.minRowBytes();
370 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
371 nullptr, nullptr)) {
372 SkDebugf("[terminated] Could not install pixels.\n");
373 return;
374 }
375 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
376 &opts, colorPtr, colorCountPtr);
377 switch (result) {
378 case SkCodec::kSuccess:
379 case SkCodec::kIncompleteInput:
380 SkDebugf("okay\n");
381 break;
382 case SkCodec::kInvalidConversion:
383 if (0 == (x|y)) {
384 // First subset is okay to return unimplemented.
385 SkDebugf("[terminated] Incompatible colortype conversion\n");
386 return;
387 }
388 // If the first subset succeeded, a later one should not fail.
389 // fall through to failure
390 case SkCodec::kUnimplemented:
391 if (0 == (x|y)) {
392 // First subset is okay to return unimplemented.
393 SkDebugf("[terminated] subset codec not supported\n");
394 return;
395 }
396 // If the first subset succeeded, why would a later one fail?
397 // fall through to failure
398 default:
399 SkDebugf("[terminated] subset codec failed to decode (%d, %d, %d, %d) "
400 "with dimensions (%d x %d)\t error %d\n",
401 x, y, decodeInfo.width(), decodeInfo.height(),
402 W, H, result);
403 return;
404 }
405 // translate by the scaled height.
406 top += decodeInfo.height();
407 }
408 // translate by the scaled width.
409 left += decodeInfo.width();
410 }
411 SkDebugf("[terminated] Success!\n");
412 break;
413 }
414 case 4: { //kAnimated_Mode
415 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
416 if (frameInfos.size() == 0) {
417 SkDebugf("[terminated] Not an animated image\n");
418 break;
419 }
420
421 for (size_t i = 0; i < frameInfos.size(); i++) {
422 options.fFrameIndex = i;
423 auto result = codec->startIncrementalDecode(decodeInfo, bitmap.getPixels(),
424 bitmap.rowBytes(), &options);
425 if (SkCodec::kSuccess != result) {
426 SkDebugf("[terminated] failed to start incremental decode "
427 "in frame %d with error %d\n", i, result);
428 return;
429 }
430
431 result = codec->incrementalDecode();
432 if (result == SkCodec::kIncompleteInput) {
433 SkDebugf("okay\n");
434 // Frames beyond this one will not decode.
435 break;
436 }
437 if (result == SkCodec::kSuccess) {
438 SkDebugf("okay - decoded frame %d\n", i);
439 } else {
440 SkDebugf("[terminated] incremental decode failed with "
441 "error %d\n", result);
442 return;
443 }
444 }
445 SkDebugf("[terminated] Success!\n");
446 break;
447 }
448 default:
449 SkDebugf("[terminated] Mode not implemented yet\n");
450 }
451
452 dump_png(bitmap);
453 }
454
fuzz_skp(sk_sp<SkData> bytes)455 static void fuzz_skp(sk_sp<SkData> bytes) {
456 SkMemoryStream stream(bytes);
457 SkDebugf("Decoding\n");
458 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(&stream));
459 if (!pic) {
460 SkDebugf("[terminated] Couldn't decode as a picture.\n");
461 return;
462 }
463 SkDebugf("Rendering\n");
464 SkBitmap bitmap;
465 if (!FLAGS_dump.isEmpty()) {
466 SkIRect size = pic->cullRect().roundOut();
467 bitmap.allocN32Pixels(size.width(), size.height());
468 }
469 SkCanvas canvas(bitmap);
470 canvas.drawPicture(pic);
471 SkDebugf("[terminated] Success! Decoded and rendered an SkPicture!\n");
472 dump_png(bitmap);
473 }
474
fuzz_icc(sk_sp<SkData> bytes)475 static void fuzz_icc(sk_sp<SkData> bytes) {
476 sk_sp<SkColorSpace> space(SkColorSpace::MakeICC(bytes->data(), bytes->size()));
477 if (!space) {
478 SkDebugf("[terminated] Couldn't decode ICC.\n");
479 return;
480 }
481 SkDebugf("[terminated] Success! Decoded ICC.\n");
482 }
483
fuzz_color_deserialize(sk_sp<SkData> bytes)484 static void fuzz_color_deserialize(sk_sp<SkData> bytes) {
485 sk_sp<SkColorSpace> space(SkColorSpace::Deserialize(bytes->data(), bytes->size()));
486 if (!space) {
487 SkDebugf("[terminated] Couldn't deserialize Colorspace.\n");
488 return;
489 }
490 SkDebugf("[terminated] Success! deserialized Colorspace.\n");
491 }
492
fuzz_path_deserialize(sk_sp<SkData> bytes)493 static void fuzz_path_deserialize(sk_sp<SkData> bytes) {
494 SkPath path;
495 if (!path.readFromMemory(bytes->data(), bytes->size())) {
496 SkDebugf("[terminated] Couldn't initialize SkPath.\n");
497 return;
498 }
499 auto s = SkSurface::MakeRasterN32Premul(1024, 1024);
500 s->getCanvas()->drawPath(path, SkPaint());
501 SkDebugf("[terminated] Success! Initialized SkPath.\n");
502 }
503
fuzz_region_deserialize(sk_sp<SkData> bytes)504 static void fuzz_region_deserialize(sk_sp<SkData> bytes) {
505 SkRegion region;
506 if (!region.readFromMemory(bytes->data(), bytes->size())) {
507 SkDebugf("[terminated] Couldn't initialize SkRegion.\n");
508 return;
509 }
510 region.computeRegionComplexity();
511 region.isComplex();
512 SkRegion r2;
513 if (region == r2) {
514 region.contains(0,0);
515 } else {
516 region.contains(1,1);
517 }
518 auto s = SkSurface::MakeRasterN32Premul(1024, 1024);
519 s->getCanvas()->drawRegion(region, SkPaint());
520 SkDEBUGCODE(region.validate());
521 SkDebugf("[terminated] Success! Initialized SkRegion.\n");
522 }
523
fuzz_filter_fuzz(sk_sp<SkData> bytes)524 static void fuzz_filter_fuzz(sk_sp<SkData> bytes) {
525
526 const int BitmapSize = 24;
527 SkBitmap bitmap;
528 bitmap.allocN32Pixels(BitmapSize, BitmapSize);
529 SkCanvas canvas(bitmap);
530 canvas.clear(0x00000000);
531
532 sk_sp<SkImageFilter> flattenable = SkValidatingDeserializeImageFilter(
533 bytes->data(), bytes->size());
534
535 // Adding some info, but the test passed if we got here without any trouble
536 if (flattenable != NULL) {
537 SkDebugf("Valid stream detected.\n");
538 // Let's see if using the filters can cause any trouble...
539 SkPaint paint;
540 paint.setImageFilter(flattenable);
541 canvas.save();
542 canvas.clipRect(SkRect::MakeXYWH(
543 0, 0, SkIntToScalar(BitmapSize), SkIntToScalar(BitmapSize)));
544
545 // This call shouldn't crash or cause ASAN to flag any memory issues
546 // If nothing bad happens within this call, everything is fine
547 canvas.drawBitmap(bitmap, 0, 0, &paint);
548
549 SkDebugf("Filter DAG rendered successfully\n");
550 canvas.restore();
551 } else {
552 SkDebugf("Invalid stream detected.\n");
553 }
554
555 SkDebugf("[terminated] Done\n");
556 }
557
558 #if SK_SUPPORT_GPU
fuzz_sksl2glsl(sk_sp<SkData> bytes)559 static void fuzz_sksl2glsl(sk_sp<SkData> bytes) {
560 SkSL::Compiler compiler;
561 SkString output;
562 SkSL::Program::Settings settings;
563 sk_sp<GrShaderCaps> caps = SkSL::ShaderCapsFactory::Default();
564 settings.fCaps = caps.get();
565 std::unique_ptr<SkSL::Program> program = compiler.convertProgram(SkSL::Program::kFragment_Kind,
566 SkString((const char*) bytes->data()),
567 settings);
568 if (!program || !compiler.toGLSL(*program, &output)) {
569 SkDebugf("[terminated] Couldn't compile input.\n");
570 return;
571 }
572 SkDebugf("[terminated] Success! Compiled input.\n");
573 }
574 #endif
575
Fuzz(sk_sp<SkData> bytes)576 Fuzz::Fuzz(sk_sp<SkData> bytes) : fBytes(bytes), fNextByte(0) {}
577
signalBug()578 void Fuzz::signalBug() { SkDebugf("Signal bug\n"); raise(SIGSEGV); }
579
size()580 size_t Fuzz::size() { return fBytes->size(); }
581
exhausted()582 bool Fuzz::exhausted() {
583 return fBytes->size() == fNextByte;
584 }
585