xref: /aosp_15_r20/external/cronet/testing/libfuzzer/fuzzers/libpng_read_fuzzer.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <assert.h>
6 #include <stddef.h>
7 #include <stdint.h>
8 
9 #include <vector>
10 
11 #include "base/functional/bind.h"
12 #include "base/functional/callback_helpers.h"
13 #define PNG_INTERNAL
14 #include "third_party/libpng/png.h"
15 
limited_malloc(png_structp,png_alloc_size_t size)16 void* limited_malloc(png_structp, png_alloc_size_t size) {
17   // libpng may allocate large amounts of memory that the fuzzer reports as
18   // an error. In order to silence these errors, make libpng fail when trying
19   // to allocate a large amount.
20   // This number is chosen to match the default png_user_chunk_malloc_max.
21   if (size > 8000000)
22     return nullptr;
23 
24   return malloc(size);
25 }
26 
default_free(png_structp,png_voidp ptr)27 void default_free(png_structp, png_voidp ptr) {
28   return free(ptr);
29 }
30 
31 static const int kPngHeaderSize = 8;
32 
33 // Entry point for LibFuzzer.
34 // Roughly follows the libpng book example:
35 // http://www.libpng.org/pub/png/book/chapter13.html
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)36 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
37   if (size < kPngHeaderSize) {
38     return 0;
39   }
40 
41   std::vector<unsigned char> v(data, data + size);
42   if (png_sig_cmp(v.data(), 0, kPngHeaderSize)) {
43     // not a PNG.
44     return 0;
45   }
46 
47   png_structp png_ptr = png_create_read_struct
48     (PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
49   assert(png_ptr);
50 
51 #ifdef MEMORY_SANITIZER
52   // To avoid OOM with MSan (crbug.com/648073). These values are recommended as
53   // safe settings by https://github.com/glennrp/libpng/blob/libpng16/pngusr.dfa
54   png_set_user_limits(png_ptr, 65535, 65535);
55 #endif
56 
57   // Not all potential OOM are due to images with large widths and heights.
58   // Use a custom allocator that fails for large allocations.
59   png_set_mem_fn(png_ptr, nullptr, limited_malloc, default_free);
60 
61   png_set_crc_action(png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
62 
63   png_infop info_ptr = png_create_info_struct(png_ptr);
64   assert(info_ptr);
65 
66   base::ScopedClosureRunner struct_deleter(
67       base::BindOnce(&png_destroy_read_struct, &png_ptr, &info_ptr, nullptr));
68 
69   if (setjmp(png_jmpbuf(png_ptr))) {
70     return 0;
71   }
72 
73   png_set_progressive_read_fn(png_ptr, nullptr, nullptr, nullptr, nullptr);
74   png_process_data(png_ptr, info_ptr, const_cast<uint8_t*>(data), size);
75 
76   return 0;
77 }
78