127b27ec6Sopenharmony_ci/**
227b27ec6Sopenharmony_ci * This fuzz target attempts to compress the fuzzed data with the simple
327b27ec6Sopenharmony_ci * compression function with an output buffer that may be too small to
427b27ec6Sopenharmony_ci * ensure that the compressor never crashes.
527b27ec6Sopenharmony_ci */
627b27ec6Sopenharmony_ci
727b27ec6Sopenharmony_ci#include <stddef.h>
827b27ec6Sopenharmony_ci#include <stdint.h>
927b27ec6Sopenharmony_ci#include <stdlib.h>
1027b27ec6Sopenharmony_ci#include <string.h>
1127b27ec6Sopenharmony_ci
1227b27ec6Sopenharmony_ci#include "fuzz_helpers.h"
1327b27ec6Sopenharmony_ci#include "lz4.h"
1427b27ec6Sopenharmony_ci#include "lz4frame.h"
1527b27ec6Sopenharmony_ci#include "lz4_helpers.h"
1627b27ec6Sopenharmony_ci#include "fuzz_data_producer.h"
1727b27ec6Sopenharmony_ci
1827b27ec6Sopenharmony_ciint LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1927b27ec6Sopenharmony_ci{
2027b27ec6Sopenharmony_ci    FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(data, size);
2127b27ec6Sopenharmony_ci    LZ4F_preferences_t const prefs = FUZZ_dataProducer_preferences(producer);
2227b27ec6Sopenharmony_ci    size_t const dstCapacitySeed = FUZZ_dataProducer_retrieve32(producer);
2327b27ec6Sopenharmony_ci    size = FUZZ_dataProducer_remainingBytes(producer);
2427b27ec6Sopenharmony_ci
2527b27ec6Sopenharmony_ci    size_t const compressBound = LZ4F_compressFrameBound(size, &prefs);
2627b27ec6Sopenharmony_ci    size_t const dstCapacity = FUZZ_getRange_from_uint32(dstCapacitySeed, 0, compressBound);
2727b27ec6Sopenharmony_ci
2827b27ec6Sopenharmony_ci    char* const dst = (char*)malloc(dstCapacity);
2927b27ec6Sopenharmony_ci    char* const rt = (char*)malloc(size);
3027b27ec6Sopenharmony_ci
3127b27ec6Sopenharmony_ci    FUZZ_ASSERT(dst!=NULL);
3227b27ec6Sopenharmony_ci    FUZZ_ASSERT(rt!=NULL);
3327b27ec6Sopenharmony_ci
3427b27ec6Sopenharmony_ci    /* If compression succeeds it must round trip correctly. */
3527b27ec6Sopenharmony_ci    size_t const dstSize =
3627b27ec6Sopenharmony_ci            LZ4F_compressFrame(dst, dstCapacity, data, size, &prefs);
3727b27ec6Sopenharmony_ci    if (!LZ4F_isError(dstSize)) {
3827b27ec6Sopenharmony_ci        size_t const rtSize = FUZZ_decompressFrame(rt, size, dst, dstSize);
3927b27ec6Sopenharmony_ci        FUZZ_ASSERT_MSG(rtSize == size, "Incorrect regenerated size");
4027b27ec6Sopenharmony_ci        FUZZ_ASSERT_MSG(!memcmp(data, rt, size), "Corruption!");
4127b27ec6Sopenharmony_ci    }
4227b27ec6Sopenharmony_ci
4327b27ec6Sopenharmony_ci    free(dst);
4427b27ec6Sopenharmony_ci    free(rt);
4527b27ec6Sopenharmony_ci    FUZZ_dataProducer_free(producer);
4627b27ec6Sopenharmony_ci
4727b27ec6Sopenharmony_ci    return 0;
4827b27ec6Sopenharmony_ci}
49