simple_compress.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2016-2021, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /**
  11. * This fuzz target attempts to comprss the fuzzed data with the simple
  12. * compression function with an output buffer that may be too small to
  13. * ensure that the compressor never crashes.
  14. */
  15. #include <stddef.h>
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include "fuzz_helpers.h"
  19. #include "zstd.h"
  20. #include "zstd_errors.h"
  21. #include "zstd_helpers.h"
  22. #include "fuzz_data_producer.h"
  23. static ZSTD_CCtx *cctx = NULL;
  24. int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
  25. {
  26. /* Give a random portion of src data to the producer, to use for
  27. parameter generation. The rest will be used for (de)compression */
  28. FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
  29. size = FUZZ_dataProducer_reserveDataPrefix(producer);
  30. size_t const maxSize = ZSTD_compressBound(size);
  31. size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, maxSize);
  32. int const cLevel = FUZZ_dataProducer_int32Range(producer, kMinClevel, kMaxClevel);
  33. if (!cctx) {
  34. cctx = ZSTD_createCCtx();
  35. FUZZ_ASSERT(cctx);
  36. }
  37. void *rBuf = FUZZ_malloc(bufSize);
  38. size_t const ret = ZSTD_compressCCtx(cctx, rBuf, bufSize, src, size, cLevel);
  39. if (ZSTD_isError(ret)) {
  40. FUZZ_ASSERT(ZSTD_getErrorCode(ret) == ZSTD_error_dstSize_tooSmall);
  41. }
  42. free(rBuf);
  43. FUZZ_dataProducer_free(producer);
  44. #ifndef STATEFUL_FUZZING
  45. ZSTD_freeCCtx(cctx); cctx = NULL;
  46. #endif
  47. return 0;
  48. }