decode_fuzzer.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 <stddef.h>
  5. #include <stdint.h>
  6. #include <stdlib.h>
  7. #include <brotli/decode.h>
  8. // Entry point for LibFuzzer.
  9. int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  10. size_t addend = 0;
  11. if (size > 0)
  12. addend = data[size - 1] & 7;
  13. const uint8_t* next_in = data;
  14. const int kBufferSize = 1024;
  15. uint8_t* buffer = (uint8_t*) malloc(kBufferSize);
  16. if (!buffer) {
  17. // OOM is out-of-scope here.
  18. return 0;
  19. }
  20. /* The biggest "magic number" in brotli is 16MiB - 16, so no need to check
  21. the cases with much longer output. */
  22. const size_t total_out_limit = (addend == 0) ? (1 << 26) : (1 << 24);
  23. size_t total_out = 0;
  24. BrotliDecoderState* state = BrotliDecoderCreateInstance(0, 0, 0);
  25. if (!state) {
  26. // OOM is out-of-scope here.
  27. free(buffer);
  28. return 0;
  29. }
  30. if (addend == 0)
  31. addend = size;
  32. /* Test both fast (addend == size) and slow (addend <= 7) decoding paths. */
  33. for (size_t i = 0; i < size;) {
  34. size_t next_i = i + addend;
  35. if (next_i > size)
  36. next_i = size;
  37. size_t avail_in = next_i - i;
  38. i = next_i;
  39. BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  40. while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  41. size_t avail_out = kBufferSize;
  42. uint8_t* next_out = buffer;
  43. result = BrotliDecoderDecompressStream(
  44. state, &avail_in, &next_in, &avail_out, &next_out, &total_out);
  45. if (total_out > total_out_limit)
  46. break;
  47. }
  48. if (total_out > total_out_limit)
  49. break;
  50. if (result != BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT)
  51. break;
  52. }
  53. BrotliDecoderDestroyInstance(state);
  54. free(buffer);
  55. return 0;
  56. }