summaryrefslogtreecommitdiffstats
path: root/src/zstd/contrib/linux-kernel/test/DecompressCrash.c
blob: 2ab7dfe528a76f843b2f1de59f4a1d1fa16e5917 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 */

/*
  This program takes a file in input,
  performs a zstd round-trip test (compression - decompress)
  compares the result with original
  and generates a crash (double free) on corruption detection.
*/

/*===========================================
*   Dependencies
*==========================================*/
#include <stddef.h>     /* size_t */
#include <stdlib.h>     /* malloc, free, exit */
#include <stdio.h>      /* fprintf */
#include <linux/zstd.h>

/*===========================================
*   Macros
*==========================================*/
#define MIN(a,b)  ( (a) < (b) ? (a) : (b) )

static ZSTD_DCtx *dctx = NULL;
void *dws = NULL;
static void* rBuff = NULL;
static size_t buffSize = 0;

static void crash(int errorCode){
    /* abort if AFL/libfuzzer, exit otherwise */
    #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* could also use __AFL_COMPILER */
        abort();
    #else
        exit(errorCode);
    #endif
}

static void decompressCheck(const void* srcBuff, size_t srcBuffSize)
{
    size_t const neededBuffSize = 20 * srcBuffSize;

    /* Allocate all buffers and contexts if not already allocated */
    if (neededBuffSize > buffSize) {
        free(rBuff);
        buffSize = 0;

        rBuff = malloc(neededBuffSize);
        if (!rBuff) {
            fprintf(stderr, "not enough memory ! \n");
            crash(1);
        }
        buffSize = neededBuffSize;
    }
    if (!dctx) {
        size_t const workspaceSize = ZSTD_DCtxWorkspaceBound();
        dws = malloc(workspaceSize);
        if (!dws) {
            fprintf(stderr, "not enough memory ! \n");
            crash(1);
        }
        dctx = ZSTD_initDCtx(dws, workspaceSize);
        if (!dctx) {
            fprintf(stderr, "not enough memory ! \n");
            crash(1);
        }
    }
    ZSTD_decompressDCtx(dctx, rBuff, buffSize, srcBuff, srcBuffSize);

#ifndef SKIP_FREE
    free(dws); dws = NULL; dctx = NULL;
    free(rBuff); rBuff = NULL;
    buffSize = 0;
#endif
}

int LLVMFuzzerTestOneInput(const unsigned char *srcBuff, size_t srcBuffSize) {
  decompressCheck(srcBuff, srcBuffSize);
  return 0;
}