dictionary_decompress.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 decompress the fuzzed data with the dictionary
  12. * decompression function to ensure the decompressor never crashes. It does not
  13. * fuzz the dictionary.
  14. */
  15. #include <stddef.h>
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include "fuzz_helpers.h"
  19. #include "zstd_helpers.h"
  20. #include "fuzz_data_producer.h"
  21. static ZSTD_DCtx *dctx = NULL;
  22. int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
  23. {
  24. /* Give a random portion of src data to the producer, to use for
  25. parameter generation. The rest will be used for (de)compression */
  26. FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
  27. size = FUZZ_dataProducer_reserveDataPrefix(producer);
  28. FUZZ_dict_t dict;
  29. ZSTD_DDict* ddict = NULL;
  30. if (!dctx) {
  31. dctx = ZSTD_createDCtx();
  32. FUZZ_ASSERT(dctx);
  33. }
  34. dict = FUZZ_train(src, size, producer);
  35. if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0) {
  36. ddict = ZSTD_createDDict(dict.buff, dict.size);
  37. FUZZ_ASSERT(ddict);
  38. } else {
  39. if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0)
  40. FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced(
  41. dctx, dict.buff, dict.size,
  42. (ZSTD_dictLoadMethod_e)FUZZ_dataProducer_uint32Range(producer, 0, 1),
  43. (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
  44. else
  45. FUZZ_ZASSERT(ZSTD_DCtx_refPrefix_advanced(
  46. dctx, dict.buff, dict.size,
  47. (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
  48. }
  49. {
  50. size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size);
  51. void* rBuf = FUZZ_malloc(bufSize);
  52. if (ddict) {
  53. ZSTD_decompress_usingDDict(dctx, rBuf, bufSize, src, size, ddict);
  54. } else {
  55. ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
  56. }
  57. free(rBuf);
  58. }
  59. free(dict.buff);
  60. FUZZ_dataProducer_free(producer);
  61. ZSTD_freeDDict(ddict);
  62. #ifndef STATEFUL_FUZZING
  63. ZSTD_freeDCtx(dctx); dctx = NULL;
  64. #endif
  65. return 0;
  66. }