libpng_read_fuzzer.cc 2.3 KB

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