• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include <assert.h>
11 #include <stddef.h>
12 #include <stdint.h>
13 
14 #include <vector>
15 
16 #include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
17 
18 #define PNG_INTERNAL
19 #include "third_party/libpng/png.h"
20 
limited_malloc(png_structp,png_alloc_size_t size)21 void* limited_malloc(png_structp, png_alloc_size_t size) {
22   // libpng may allocate large amounts of memory that the fuzzer reports as
23   // an error. In order to silence these errors, make libpng fail when trying
24   // to allocate a large amount.
25   // This number is chosen to match the default png_user_chunk_malloc_max.
26   if (size > 8000000)
27     return nullptr;
28 
29   return malloc(size);
30 }
31 
default_free(png_structp,png_voidp ptr)32 void default_free(png_structp, png_voidp ptr) {
33   return free(ptr);
34 }
35 
36 static const int kPngHeaderSize = 8;
37 
38 // Entry point for LibFuzzer.
39 // Roughly follows the libpng book example:
40 // http://www.libpng.org/pub/png/book/chapter13.html
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)41 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
42   if (size < kPngHeaderSize) {
43     return 0;
44   }
45 
46   std::vector<unsigned char> v(data, data + size);
47   if (png_sig_cmp(v.data(), 0, kPngHeaderSize)) {
48     // not a PNG.
49     return 0;
50   }
51 
52   png_structp png_ptr = png_create_read_struct
53     (PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
54   assert(png_ptr);
55 
56 #ifdef MEMORY_SANITIZER
57   // To avoid OOM with MSan (crbug.com/648073). These values are recommended as
58   // safe settings by https://github.com/glennrp/libpng/blob/libpng16/pngusr.dfa
59   png_set_user_limits(png_ptr, 65535, 65535);
60 #endif
61 
62   // Not all potential OOM are due to images with large widths and heights.
63   // Use a custom allocator that fails for large allocations.
64   png_set_mem_fn(png_ptr, nullptr, limited_malloc, default_free);
65 
66   png_set_crc_action(png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
67 
68   png_infop info_ptr = png_create_info_struct(png_ptr);
69   assert(info_ptr);
70 
71   absl::Cleanup struct_deleter = [&png_ptr, &info_ptr] {
72     png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
73   };
74 
75   if (setjmp(png_jmpbuf(png_ptr))) {
76     return 0;
77   }
78 
79   png_set_progressive_read_fn(png_ptr, nullptr, nullptr, nullptr, nullptr);
80   png_process_data(png_ptr, info_ptr, const_cast<uint8_t*>(data), size);
81 
82   return 0;
83 }
84