• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Fuzz.h"
9 #include "include/codec/SkCodec.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkImage.h"
13 #include "include/core/SkImageEncoder.h"
14 #include "include/core/SkMallocPixelRef.h"
15 #include "include/core/SkPaint.h"
16 #include "include/core/SkPath.h"
17 #include "include/core/SkStream.h"
18 #include "include/core/SkSurface.h"
19 #include "include/core/SkTextBlob.h"
20 #include "src/core/SkFontMgrPriv.h"
21 #include "src/core/SkOSFile.h"
22 #include "src/core/SkReadBuffer.h"
23 #include "src/utils/SkOSPath.h"
24 #include "tools/ToolUtils.h"
25 #include "tools/flags/CommandLineFlags.h"
26 #include "tools/fonts/TestFontMgr.h"
27 
28 #include <iostream>
29 #include <map>
30 #include <regex>
31 #include <signal.h>
32 
33 static DEFINE_string2(bytes, b, "", "A path to a file or a directory. If a file, the "
34                       "contents will be used as the fuzz bytes. If a directory, all files "
35                       "in the directory will be used as fuzz bytes for the fuzzer, one at a "
36                       "time.");
37 static DEFINE_string2(name, n, "", "If --type is 'api', fuzz the API with this name.");
38 static DEFINE_string2(dump, d, "", "If not empty, dump 'image*' or 'skp' types as a "
39                                    "PNG with this name.");
40 static DEFINE_int(loops, 1, "Run the fuzzer on each input this many times.");
41 DEFINE_bool2(verbose, v, false, "Print more information while fuzzing.");
42 
43 // This cannot be inlined in DEFINE_string2 due to interleaved ifdefs
44 static constexpr char g_type_message[] = "How to interpret --bytes, one of:\n"
45                                          "android_codec\n"
46                                          "animated_image_decode\n"
47                                          "api\n"
48                                          "color_deserialize\n"
49                                          "filter_fuzz (equivalent to Chrome's filter_fuzz_stub)\n"
50                                          "image_decode\n"
51                                          "image_decode_incremental\n"
52                                          "image_mode\n"
53                                          "image_scale\n"
54                                          "json\n"
55                                          "path_deserialize\n"
56                                          "region_deserialize\n"
57                                          "region_set_path\n"
58                                          "skdescriptor_deserialize\n"
59                                          "skp\n"
60                                          "skruntimeeffect\n"
61                                          "sksl2glsl\n"
62                                          "svg_dom\n"
63                                          "sksl2metal\n"
64                                          "sksl2pipeline\n"
65                                          "sksl2spirv\n"
66 #if defined(SK_ENABLE_SKOTTIE)
67                                          "skottie_json\n"
68 #endif
69                                          "textblob";
70 
71 static DEFINE_string2(type, t, "", g_type_message);
72 
73 static int fuzz_file(SkString path, SkString type);
74 static uint8_t calculate_option(SkData*);
75 static SkString try_auto_detect(SkString path, SkString* name);
76 
77 static void fuzz_android_codec(sk_sp<SkData>);
78 static void fuzz_animated_img(sk_sp<SkData>);
79 static void fuzz_api(sk_sp<SkData> bytes, SkString name);
80 static void fuzz_color_deserialize(sk_sp<SkData>);
81 static void fuzz_filter_fuzz(sk_sp<SkData>);
82 static void fuzz_image_decode(sk_sp<SkData>);
83 static void fuzz_image_decode_incremental(sk_sp<SkData>);
84 static void fuzz_img(sk_sp<SkData>, uint8_t, uint8_t);
85 static void fuzz_json(sk_sp<SkData>);
86 static void fuzz_path_deserialize(sk_sp<SkData>);
87 static void fuzz_region_deserialize(sk_sp<SkData>);
88 static void fuzz_region_set_path(sk_sp<SkData>);
89 static void fuzz_skdescriptor_deserialize(sk_sp<SkData>);
90 static void fuzz_skp(sk_sp<SkData>);
91 static void fuzz_skruntimeeffect(sk_sp<SkData>);
92 static void fuzz_sksl2glsl(sk_sp<SkData>);
93 static void fuzz_sksl2metal(sk_sp<SkData>);
94 static void fuzz_sksl2pipeline(sk_sp<SkData>);
95 static void fuzz_sksl2spirv(sk_sp<SkData>);
96 static void fuzz_textblob_deserialize(sk_sp<SkData>);
97 
98 static void print_api_names();
99 
100 #if defined(SK_ENABLE_SVG)
101 static void fuzz_svg_dom(sk_sp<SkData>);
102 #endif
103 
104 #if defined(SK_ENABLE_SKOTTIE)
105 static void fuzz_skottie_json(sk_sp<SkData>);
106 #endif
107 
main(int argc,char ** argv)108 int main(int argc, char** argv) {
109     CommandLineFlags::SetUsage(
110             "Usage: fuzz -t <type> -b <path/to/file> [-n api-to-fuzz]\n"
111             "       fuzz -b <path/to/file>\n"
112             "--help lists the valid types. If type is not specified,\n"
113             "fuzz will make a guess based on the name of the file.\n");
114     CommandLineFlags::Parse(argc, argv);
115     gSkFontMgr_DefaultFactory = &ToolUtils::MakePortableFontMgr;
116 
117     SkString path = SkString(FLAGS_bytes.isEmpty() ? argv[0] : FLAGS_bytes[0]);
118     SkString type = SkString(FLAGS_type.isEmpty() ? "" : FLAGS_type[0]);
119 
120     int loopCount = std::max(FLAGS_loops, 1);
121 
122     if (!sk_isdir(path.c_str())) {
123         for (int i = 0; i < loopCount; ++i) {
124             int rv = fuzz_file(path, type);
125             if (rv != 0) {
126                 return rv;
127             }
128         }
129         return 0;
130     }
131 
132     SkOSFile::Iter it(path.c_str());
133     for (SkString file; it.next(&file); ) {
134         SkString p = SkOSPath::Join(path.c_str(), file.c_str());
135         SkDebugf("Fuzzing %s\n", p.c_str());
136         for (int i = 0; i < loopCount; ++i) {
137             int rv = fuzz_file(p, type);
138             if (rv != 0) {
139                 return rv;
140             }
141         }
142     }
143     return 0;
144 }
145 
fuzz_file(SkString path,SkString type)146 static int fuzz_file(SkString path, SkString type) {
147     sk_sp<SkData> bytes(SkData::MakeFromFileName(path.c_str()));
148     if (!bytes) {
149         SkDebugf("Could not read %s\n", path.c_str());
150         return 1;
151     }
152 
153     SkString name = SkString(FLAGS_name.isEmpty() ? "" : FLAGS_name[0]);
154 
155     if (type.isEmpty()) {
156         type = try_auto_detect(path, &name);
157     }
158 
159     if (type.isEmpty()) {
160         SkDebugf("Could not autodetect type of %s\n", path.c_str());
161         return 1;
162     }
163     if (type.equals("android_codec")) {
164         fuzz_android_codec(bytes);
165         return 0;
166     }
167     if (type.equals("animated_image_decode")) {
168         fuzz_animated_img(bytes);
169         return 0;
170     }
171     if (type.equals("api")) {
172         fuzz_api(bytes, name);
173         return 0;
174     }
175     if (type.equals("color_deserialize")) {
176         fuzz_color_deserialize(bytes);
177         return 0;
178     }
179     if (type.equals("filter_fuzz")) {
180         fuzz_filter_fuzz(bytes);
181         return 0;
182     }
183     if (type.equals("image_decode")) {
184         fuzz_image_decode(bytes);
185         return 0;
186     }
187     if (type.equals("image_decode_incremental")) {
188         fuzz_image_decode_incremental(bytes);
189         return 0;
190     }
191     if (type.equals("image_scale")) {
192         uint8_t option = calculate_option(bytes.get());
193         fuzz_img(bytes, option, 0);
194         return 0;
195     }
196     if (type.equals("image_mode")) {
197         uint8_t option = calculate_option(bytes.get());
198         fuzz_img(bytes, 0, option);
199         return 0;
200     }
201     if (type.equals("json")) {
202         fuzz_json(bytes);
203         return 0;
204     }
205     if (type.equals("path_deserialize")) {
206         fuzz_path_deserialize(bytes);
207         return 0;
208     }
209     if (type.equals("region_deserialize")) {
210         fuzz_region_deserialize(bytes);
211         return 0;
212     }
213     if (type.equals("region_set_path")) {
214         fuzz_region_set_path(bytes);
215         return 0;
216     }
217     if (type.equals("pipe")) {
218         SkDebugf("I would prefer not to.\n");
219         return 0;
220     }
221     if (type.equals("skdescriptor_deserialize")) {
222         fuzz_skdescriptor_deserialize(bytes);
223         return 0;
224     }
225 #if defined(SK_ENABLE_SKOTTIE)
226     if (type.equals("skottie_json")) {
227         fuzz_skottie_json(bytes);
228         return 0;
229     }
230 #endif
231     if (type.equals("skp")) {
232         fuzz_skp(bytes);
233         return 0;
234     }
235     if (type.equals("skruntimeeffect")) {
236         fuzz_skruntimeeffect(bytes);
237         return 0;
238     }
239     if (type.equals("sksl2glsl")) {
240         fuzz_sksl2glsl(bytes);
241         return 0;
242     }
243     if (type.equals("sksl2metal")) {
244         fuzz_sksl2metal(bytes);
245         return 0;
246     }
247     if (type.equals("sksl2spirv")) {
248         fuzz_sksl2spirv(bytes);
249         return 0;
250     }
251     if (type.equals("sksl2pipeline")) {
252         fuzz_sksl2pipeline(bytes);
253         return 0;
254     }
255 #if defined(SK_ENABLE_SVG)
256     if (type.equals("svg_dom")) {
257         fuzz_svg_dom(bytes);
258         return 0;
259     }
260 #endif
261     if (type.equals("textblob")) {
262         fuzz_textblob_deserialize(bytes);
263         return 0;
264     }
265     SkDebugf("Unknown type %s\n", type.c_str());
266     CommandLineFlags::PrintUsage();
267     return 1;
268 }
269 
270 static std::map<std::string, std::string> cf_api_map = {
271     {"api_create_ddl", "CreateDDL"},
272     {"api_draw_functions", "DrawFunctions"},
273     {"api_ddl_threading", "DDLThreadingGL"},
274     {"api_gradients", "Gradients"},
275     {"api_image_filter", "ImageFilter"},
276     {"api_mock_gpu_canvas", "MockGPUCanvas"},
277     {"api_null_canvas", "NullCanvas"},
278     {"api_path_measure", "PathMeasure"},
279     {"api_pathop", "Pathop"},
280     {"api_polyutils", "PolyUtils"},
281     {"api_raster_n32_canvas", "RasterN32Canvas"},
282     {"api_skparagraph", "SkParagraph"},
283     {"api_svg_canvas", "SVGCanvas"},
284     {"jpeg_encoder", "JPEGEncoder"},
285     {"png_encoder", "PNGEncoder"},
286     {"skia_pathop_fuzzer", "LegacyChromiumPathop"},
287     {"webp_encoder", "WEBPEncoder"}
288 };
289 
290 // maps clusterfuzz/oss-fuzz -> Skia's name
291 static std::map<std::string, std::string> cf_map = {
292     {"android_codec", "android_codec"},
293     {"animated_image_decode", "animated_image_decode"},
294     {"image_decode", "image_decode"},
295     {"image_decode_incremental", "image_decode_incremental"},
296     {"image_filter_deserialize", "filter_fuzz"},
297     {"image_filter_deserialize_width", "filter_fuzz"},
298     {"path_deserialize", "path_deserialize"},
299     {"region_deserialize", "region_deserialize"},
300     {"region_set_path", "region_set_path"},
301     {"skdescriptor_deserialize", "skdescriptor_deserialize"},
302     {"skjson", "json"},
303     {"skp", "skp"},
304     {"skruntimeeffect", "skruntimeeffect"},
305     {"sksl2glsl", "sksl2glsl"},
306     {"sksl2metal", "sksl2metal"},
307     {"sksl2spirv", "sksl2spirv"},
308     {"sksl2pipeline", "sksl2pipeline"},
309 #if defined(SK_ENABLE_SKOTTIE)
310     {"skottie_json", "skottie_json"},
311 #endif
312 #if defined(SK_ENABLE_SVG)
313     {"svg_dom", "svg_dom"},
314 #endif
315     {"textblob_deserialize", "textblob"}
316 };
317 
try_auto_detect(SkString path,SkString * name)318 static SkString try_auto_detect(SkString path, SkString* name) {
319     std::cmatch m;
320     std::regex clusterfuzz("clusterfuzz-testcase(-minimized)?-([a-z0-9_]+)-[\\d]+");
321     std::regex skiafuzzer("(api-)?(\\w+)-[a-f0-9]+");
322 
323     if (std::regex_search(path.c_str(), m, clusterfuzz)) {
324         std::string type = m.str(2);
325 
326         if (cf_api_map.find(type) != cf_api_map.end()) {
327             *name = SkString(cf_api_map[type].c_str());
328             return SkString("api");
329         } else {
330             if (cf_map.find(type) != cf_map.end()) {
331                 return SkString(cf_map[type].c_str());
332             }
333         }
334     } else if (std::regex_search(path.c_str(), m, skiafuzzer)) {
335         std::string a1 = m.str(1);
336         std::string typeOrName = m.str(2);
337         if (a1.length() > 0) {
338             // it's an api fuzzer
339             *name = SkString(typeOrName.c_str());
340             return SkString("api");
341         } else {
342             return SkString(typeOrName.c_str());
343         }
344     }
345 
346     return SkString("");
347 }
348 
349 void FuzzJSON(sk_sp<SkData> bytes);
350 
fuzz_json(sk_sp<SkData> bytes)351 static void fuzz_json(sk_sp<SkData> bytes){
352     FuzzJSON(bytes);
353     SkDebugf("[terminated] Done parsing!\n");
354 }
355 
356 #if defined(SK_ENABLE_SKOTTIE)
357 void FuzzSkottieJSON(sk_sp<SkData> bytes);
358 
fuzz_skottie_json(sk_sp<SkData> bytes)359 static void fuzz_skottie_json(sk_sp<SkData> bytes){
360     FuzzSkottieJSON(bytes);
361     SkDebugf("[terminated] Done animating!\n");
362 }
363 #endif
364 
365 #if defined(SK_ENABLE_SVG)
366 void FuzzSVG(sk_sp<SkData> bytes);
367 
fuzz_svg_dom(sk_sp<SkData> bytes)368 static void fuzz_svg_dom(sk_sp<SkData> bytes){
369     FuzzSVG(bytes);
370     SkDebugf("[terminated] Done DOM!\n");
371 }
372 #endif
373 
374 // This adds up the first 1024 bytes and returns it as an 8 bit integer.  This allows afl-fuzz to
375 // deterministically excercise different paths, or *options* (such as different scaling sizes or
376 // different image modes) without needing to introduce a parameter.  This way we don't need a
377 // image_scale1, image_scale2, image_scale4, etc fuzzer, we can just have a image_scale fuzzer.
378 // Clients are expected to transform this number into a different range, e.g. with modulo (%).
calculate_option(SkData * bytes)379 static uint8_t calculate_option(SkData* bytes) {
380     uint8_t total = 0;
381     const uint8_t* data = bytes->bytes();
382     for (size_t i = 0; i < 1024 && i < bytes->size(); i++) {
383         total += data[i];
384     }
385     return total;
386 }
387 
print_api_names()388 static void print_api_names(){
389     SkDebugf("When using --type api, please choose an API to fuzz with --name/-n:\n");
390     for (const Fuzzable& fuzzable : sk_tools::Registry<Fuzzable>::Range()) {
391         SkDebugf("\t%s\n", fuzzable.name);
392     }
393 }
394 
fuzz_api(sk_sp<SkData> bytes,SkString name)395 static void fuzz_api(sk_sp<SkData> bytes, SkString name) {
396     for (const Fuzzable& fuzzable : sk_tools::Registry<Fuzzable>::Range()) {
397         if (name.equals(fuzzable.name)) {
398             SkDebugf("Fuzzing %s...\n", fuzzable.name);
399             Fuzz fuzz(std::move(bytes));
400             fuzzable.fn(&fuzz);
401             SkDebugf("[terminated] Success!\n");
402             return;
403         }
404     }
405 
406     print_api_names();
407 }
408 
dump_png(SkBitmap bitmap)409 static void dump_png(SkBitmap bitmap) {
410     if (!FLAGS_dump.isEmpty()) {
411         ToolUtils::EncodeImageToFile(FLAGS_dump[0], bitmap, SkEncodedImageFormat::kPNG, 100);
412         SkDebugf("Dumped to %s\n", FLAGS_dump[0]);
413     }
414 }
415 
416 bool FuzzAnimatedImage(sk_sp<SkData> bytes);
417 
fuzz_animated_img(sk_sp<SkData> bytes)418 static void fuzz_animated_img(sk_sp<SkData> bytes) {
419     if (FuzzAnimatedImage(bytes)) {
420         SkDebugf("[terminated] Success from decoding/drawing animated image!\n");
421         return;
422     }
423     SkDebugf("[terminated] Could not decode or draw animated image.\n");
424 }
425 
426 bool FuzzImageDecode(sk_sp<SkData> bytes);
427 
fuzz_image_decode(sk_sp<SkData> bytes)428 static void fuzz_image_decode(sk_sp<SkData> bytes) {
429     if (FuzzImageDecode(bytes)) {
430          SkDebugf("[terminated] Success from decoding/drawing image!\n");
431          return;
432     }
433     SkDebugf("[terminated] Could not decode or draw image.\n");
434 }
435 
436 bool FuzzIncrementalImageDecode(sk_sp<SkData> bytes);
437 
fuzz_image_decode_incremental(sk_sp<SkData> bytes)438 static void fuzz_image_decode_incremental(sk_sp<SkData> bytes) {
439     if (FuzzIncrementalImageDecode(bytes)) {
440         SkDebugf("[terminated] Success using incremental decode!\n");
441         return;
442     }
443     SkDebugf("[terminated] Could not incrementally decode and image.\n");
444 }
445 
446 bool FuzzAndroidCodec(sk_sp<SkData> bytes, uint8_t sampleSize);
447 
fuzz_android_codec(sk_sp<SkData> bytes)448 static void fuzz_android_codec(sk_sp<SkData> bytes) {
449     Fuzz fuzz(bytes);
450     uint8_t sampleSize;
451     fuzz.nextRange(&sampleSize, 1, 64);
452     bytes = SkData::MakeSubset(bytes.get(), 1, bytes->size() - 1);
453     if (FuzzAndroidCodec(bytes, sampleSize)) {
454         SkDebugf("[terminated] Success on Android Codec sampleSize=%u!\n", sampleSize);
455         return;
456     }
457     SkDebugf("[terminated] Could not use Android Codec sampleSize=%u!\n", sampleSize);
458 }
459 
460 // This is a "legacy" fuzzer that likely does too much. It was based off of how
461 // DM reads in images. image_decode, image_decode_incremental and android_codec
462 // are more targeted fuzzers that do a subset of what this one does.
fuzz_img(sk_sp<SkData> bytes,uint8_t scale,uint8_t mode)463 static void fuzz_img(sk_sp<SkData> bytes, uint8_t scale, uint8_t mode) {
464     // We can scale 1x, 2x, 4x, 8x, 16x
465     scale = scale % 5;
466     float fscale = (float)pow(2.0f, scale);
467     SkDebugf("Scaling factor: %f\n", fscale);
468 
469     // We have 5 different modes of decoding.
470     mode = mode % 5;
471     SkDebugf("Mode: %d\n", mode);
472 
473     // This is mostly copied from DMSrcSink's CodecSrc::draw method.
474     SkDebugf("Decoding\n");
475     std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(bytes));
476     if (nullptr == codec) {
477         SkDebugf("[terminated] Couldn't create codec.\n");
478         return;
479     }
480 
481     SkImageInfo decodeInfo = codec->getInfo();
482     SkISize size = codec->getScaledDimensions(fscale);
483     decodeInfo = decodeInfo.makeDimensions(size);
484 
485     SkBitmap bitmap;
486     SkCodec::Options options;
487     options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
488 
489     if (!bitmap.tryAllocPixelsFlags(decodeInfo, SkBitmap::kZeroPixels_AllocFlag)) {
490         SkDebugf("[terminated] Could not allocate memory.  Image might be too large (%d x %d)",
491                  decodeInfo.width(), decodeInfo.height());
492         return;
493     }
494 
495     switch (mode) {
496         case 0: {//kCodecZeroInit_Mode, kCodec_Mode
497             switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), &options)) {
498                 case SkCodec::kSuccess:
499                     SkDebugf("[terminated] Success!\n");
500                     break;
501                 case SkCodec::kIncompleteInput:
502                     SkDebugf("[terminated] Partial Success\n");
503                     break;
504                 case SkCodec::kErrorInInput:
505                     SkDebugf("[terminated] Partial Success with error\n");
506                     break;
507                 case SkCodec::kInvalidConversion:
508                     SkDebugf("Incompatible colortype conversion\n");
509                     // Crash to allow afl-fuzz to know this was a bug.
510                     raise(SIGSEGV);
511                     break;
512                 default:
513                     SkDebugf("[terminated] Couldn't getPixels.\n");
514                     return;
515             }
516             break;
517         }
518         case 1: {//kScanline_Mode
519             if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
520                 SkDebugf("[terminated] Could not start scanline decoder\n");
521                 return;
522             }
523 
524             void* dst = bitmap.getAddr(0, 0);
525             size_t rowBytes = bitmap.rowBytes();
526             uint32_t height = decodeInfo.height();
527             // We do not need to check the return value.  On an incomplete
528             // image, memory will be filled with a default value.
529             codec->getScanlines(dst, height, rowBytes);
530             SkDebugf("[terminated] Success!\n");
531             break;
532         }
533         case 2: { //kStripe_Mode
534             const int height = decodeInfo.height();
535             // This value is chosen arbitrarily.  We exercise more cases by choosing a value that
536             // does not align with image blocks.
537             const int stripeHeight = 37;
538             const int numStripes = (height + stripeHeight - 1) / stripeHeight;
539 
540             // Decode odd stripes
541             if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)
542                     || SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
543                 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
544                 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
545                 // to run this test for image types that do not have this scanline ordering.
546                 SkDebugf("[terminated] Could not start top-down scanline decoder\n");
547                 return;
548             }
549 
550             for (int i = 0; i < numStripes; i += 2) {
551                 // Skip a stripe
552                 const int linesToSkip = std::min(stripeHeight, height - i * stripeHeight);
553                 codec->skipScanlines(linesToSkip);
554 
555                 // Read a stripe
556                 const int startY = (i + 1) * stripeHeight;
557                 const int linesToRead = std::min(stripeHeight, height - startY);
558                 if (linesToRead > 0) {
559                     codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
560                 }
561             }
562 
563             // Decode even stripes
564             const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
565             if (SkCodec::kSuccess != startResult) {
566                 SkDebugf("[terminated] Failed to restart scanline decoder with same parameters.\n");
567                 return;
568             }
569             for (int i = 0; i < numStripes; i += 2) {
570                 // Read a stripe
571                 const int startY = i * stripeHeight;
572                 const int linesToRead = std::min(stripeHeight, height - startY);
573                 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
574 
575                 // Skip a stripe
576                 const int linesToSkip = std::min(stripeHeight, height - (i + 1) * stripeHeight);
577                 if (linesToSkip > 0) {
578                     codec->skipScanlines(linesToSkip);
579                 }
580             }
581             SkDebugf("[terminated] Success!\n");
582             break;
583         }
584         case 3: { //kSubset_Mode
585             // Arbitrarily choose a divisor.
586             int divisor = 2;
587             // Total width/height of the image.
588             const int W = codec->getInfo().width();
589             const int H = codec->getInfo().height();
590             if (divisor > W || divisor > H) {
591                 SkDebugf("[terminated] Cannot codec subset: divisor %d is too big "
592                          "with dimensions (%d x %d)\n", divisor, W, H);
593                 return;
594             }
595             // subset dimensions
596             // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
597             const int w = SkAlign2(W / divisor);
598             const int h = SkAlign2(H / divisor);
599             SkIRect subset;
600             SkCodec::Options opts;
601             opts.fSubset = &subset;
602             SkBitmap subsetBm;
603             // We will reuse pixel memory from bitmap.
604             void* pixels = bitmap.getPixels();
605             for (int x = 0; x < W; x += w) {
606                 for (int y = 0; y < H; y+= h) {
607                     // Do not make the subset go off the edge of the image.
608                     const int preScaleW = std::min(w, W - x);
609                     const int preScaleH = std::min(h, H - y);
610                     subset.setXYWH(x, y, preScaleW, preScaleH);
611                     // And fscale
612                     // FIXME: Should we have a version of getScaledDimensions that takes a subset
613                     // into account?
614                     decodeInfo = decodeInfo.makeWH(
615                             std::max(1, SkScalarRoundToInt(preScaleW * fscale)),
616                             std::max(1, SkScalarRoundToInt(preScaleH * fscale)));
617                     size_t rowBytes = decodeInfo.minRowBytes();
618                     if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes)) {
619                         SkDebugf("[terminated] Could not install pixels.\n");
620                         return;
621                     }
622                     const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
623                             &opts);
624                     switch (result) {
625                         case SkCodec::kSuccess:
626                         case SkCodec::kIncompleteInput:
627                         case SkCodec::kErrorInInput:
628                             SkDebugf("okay\n");
629                             break;
630                         case SkCodec::kInvalidConversion:
631                             if (0 == (x|y)) {
632                                 // First subset is okay to return unimplemented.
633                                 SkDebugf("[terminated] Incompatible colortype conversion\n");
634                                 return;
635                             }
636                             // If the first subset succeeded, a later one should not fail.
637                             [[fallthrough]];
638                         case SkCodec::kUnimplemented:
639                             if (0 == (x|y)) {
640                                 // First subset is okay to return unimplemented.
641                                 SkDebugf("[terminated] subset codec not supported\n");
642                                 return;
643                             }
644                             // If the first subset succeeded, why would a later one fail?
645                             [[fallthrough]];
646                         default:
647                             SkDebugf("[terminated] subset codec failed to decode (%d, %d, %d, %d) "
648                                                   "with dimensions (%d x %d)\t error %d\n",
649                                                   x, y, decodeInfo.width(), decodeInfo.height(),
650                                                   W, H, result);
651                             return;
652                     }
653                 }
654             }
655             SkDebugf("[terminated] Success!\n");
656             break;
657         }
658         case 4: { //kAnimated_Mode
659             std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
660             if (frameInfos.size() == 0) {
661                 SkDebugf("[terminated] Not an animated image\n");
662                 break;
663             }
664 
665             for (size_t i = 0; i < frameInfos.size(); i++) {
666                 options.fFrameIndex = i;
667                 auto result = codec->startIncrementalDecode(decodeInfo, bitmap.getPixels(),
668                         bitmap.rowBytes(), &options);
669                 if (SkCodec::kSuccess != result) {
670                     SkDebugf("[terminated] failed to start incremental decode "
671                              "in frame %zu with error %d\n", i, result);
672                     return;
673                 }
674 
675                 result = codec->incrementalDecode();
676                 if (result == SkCodec::kIncompleteInput || result == SkCodec::kErrorInInput) {
677                     SkDebugf("okay\n");
678                     // Frames beyond this one will not decode.
679                     break;
680                 }
681                 if (result == SkCodec::kSuccess) {
682                     SkDebugf("okay - decoded frame %zu\n", i);
683                 } else {
684                     SkDebugf("[terminated] incremental decode failed with "
685                              "error %d\n", result);
686                     return;
687                 }
688             }
689             SkDebugf("[terminated] Success!\n");
690             break;
691         }
692         default:
693             SkDebugf("[terminated] Mode not implemented yet\n");
694     }
695 
696     dump_png(bitmap);
697 }
698 
699 void FuzzSKP(sk_sp<SkData> bytes);
fuzz_skp(sk_sp<SkData> bytes)700 static void fuzz_skp(sk_sp<SkData> bytes) {
701     FuzzSKP(bytes);
702     SkDebugf("[terminated] Finished SKP\n");
703 }
704 
fuzz_color_deserialize(sk_sp<SkData> bytes)705 static void fuzz_color_deserialize(sk_sp<SkData> bytes) {
706     sk_sp<SkColorSpace> space(SkColorSpace::Deserialize(bytes->data(), bytes->size()));
707     if (!space) {
708         SkDebugf("[terminated] Couldn't deserialize Colorspace.\n");
709         return;
710     }
711     SkDebugf("[terminated] Success! deserialized Colorspace.\n");
712 }
713 
714 void FuzzPathDeserialize(SkReadBuffer& buf);
715 
fuzz_path_deserialize(sk_sp<SkData> bytes)716 static void fuzz_path_deserialize(sk_sp<SkData> bytes) {
717     SkReadBuffer buf(bytes->data(), bytes->size());
718     FuzzPathDeserialize(buf);
719     SkDebugf("[terminated] path_deserialize didn't crash!\n");
720 }
721 
722 bool FuzzRegionDeserialize(sk_sp<SkData> bytes);
723 
fuzz_region_deserialize(sk_sp<SkData> bytes)724 static void fuzz_region_deserialize(sk_sp<SkData> bytes) {
725     if (!FuzzRegionDeserialize(bytes)) {
726         SkDebugf("[terminated] Couldn't initialize SkRegion.\n");
727         return;
728     }
729     SkDebugf("[terminated] Success! Initialized SkRegion.\n");
730 }
731 
732 void FuzzTextBlobDeserialize(SkReadBuffer& buf);
733 
fuzz_textblob_deserialize(sk_sp<SkData> bytes)734 static void fuzz_textblob_deserialize(sk_sp<SkData> bytes) {
735     SkReadBuffer buf(bytes->data(), bytes->size());
736     FuzzTextBlobDeserialize(buf);
737     SkDebugf("[terminated] textblob didn't crash!\n");
738 }
739 
740 void FuzzRegionSetPath(Fuzz* fuzz);
741 
fuzz_region_set_path(sk_sp<SkData> bytes)742 static void fuzz_region_set_path(sk_sp<SkData> bytes) {
743     Fuzz fuzz(bytes);
744     FuzzRegionSetPath(&fuzz);
745     SkDebugf("[terminated] region_set_path didn't crash!\n");
746 }
747 
748 void FuzzImageFilterDeserialize(sk_sp<SkData> bytes);
749 
fuzz_filter_fuzz(sk_sp<SkData> bytes)750 static void fuzz_filter_fuzz(sk_sp<SkData> bytes) {
751     FuzzImageFilterDeserialize(bytes);
752     SkDebugf("[terminated] filter_fuzz didn't crash!\n");
753 }
754 
755 bool FuzzSkRuntimeEffect(sk_sp<SkData> bytes);
756 
fuzz_skruntimeeffect(sk_sp<SkData> bytes)757 static void fuzz_skruntimeeffect(sk_sp<SkData> bytes) {
758     if (FuzzSkRuntimeEffect(bytes)) {
759         SkDebugf("[terminated] Success! Compiled and Executed sksl code.\n");
760     } else {
761         SkDebugf("[terminated] Could not Compile or Execute sksl code.\n");
762     }
763 }
764 
765 bool FuzzSKSL2GLSL(sk_sp<SkData> bytes);
766 
fuzz_sksl2glsl(sk_sp<SkData> bytes)767 static void fuzz_sksl2glsl(sk_sp<SkData> bytes) {
768     if (FuzzSKSL2GLSL(bytes)) {
769         SkDebugf("[terminated] Success! Compiled input to GLSL.\n");
770     } else {
771         SkDebugf("[terminated] Could not compile input to GLSL.\n");
772     }
773 }
774 
775 bool FuzzSKSL2SPIRV(sk_sp<SkData> bytes);
776 
fuzz_sksl2spirv(sk_sp<SkData> bytes)777 static void fuzz_sksl2spirv(sk_sp<SkData> bytes) {
778     if (FuzzSKSL2SPIRV(bytes)) {
779         SkDebugf("[terminated] Success! Compiled input to SPIRV.\n");
780     } else {
781         SkDebugf("[terminated] Could not compile input to SPIRV.\n");
782     }
783 }
784 
785 bool FuzzSKSL2Metal(sk_sp<SkData> bytes);
786 
fuzz_sksl2metal(sk_sp<SkData> bytes)787 static void fuzz_sksl2metal(sk_sp<SkData> bytes) {
788     if (FuzzSKSL2Metal(bytes)) {
789         SkDebugf("[terminated] Success! Compiled input to Metal.\n");
790     } else {
791         SkDebugf("[terminated] Could not compile input to Metal.\n");
792     }
793 }
794 
795 bool FuzzSKSL2Pipeline(sk_sp<SkData> bytes);
796 
fuzz_sksl2pipeline(sk_sp<SkData> bytes)797 static void fuzz_sksl2pipeline(sk_sp<SkData> bytes) {
798     if (FuzzSKSL2Pipeline(bytes)) {
799         SkDebugf("[terminated] Success! Compiled input to pipeline stage.\n");
800     } else {
801         SkDebugf("[terminated] Could not compile input to pipeline stage.\n");
802     }
803 }
804 
805 void FuzzSkDescriptorDeserialize(sk_sp<SkData> bytes);
806 
fuzz_skdescriptor_deserialize(sk_sp<SkData> bytes)807 static void fuzz_skdescriptor_deserialize(sk_sp<SkData> bytes) {
808     FuzzSkDescriptorDeserialize(bytes);
809     SkDebugf("[terminated] Did not crash while deserializing an SkDescriptor.\n");
810 }
811 
812