1 /**
2  * Copyright (c) 2016-present, Yann Collet, 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  */
9 
10 /*
11   This program takes a file in input,
12   performs a zstd round-trip test (compression - decompress)
13   compares the result with original
14   and generates a crash (double free) on corruption detection.
15 */
16 
17 /*===========================================
18 *   Dependencies
19 *==========================================*/
20 #include <stddef.h>     /* size_t */
21 #include <stdlib.h>     /* malloc, free, exit */
22 #include <stdio.h>      /* fprintf */
23 #include <linux/zstd.h>
24 
25 /*===========================================
26 *   Macros
27 *==========================================*/
28 #define MIN(a,b)  ( (a) < (b) ? (a) : (b) )
29 
30 static ZSTD_DCtx *dctx = NULL;
31 void *dws = NULL;
32 static void* rBuff = NULL;
33 static size_t buffSize = 0;
34 
crash(int errorCode)35 static void crash(int errorCode){
36     /* abort if AFL/libfuzzer, exit otherwise */
37     #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* could also use __AFL_COMPILER */
38         abort();
39     #else
40         exit(errorCode);
41     #endif
42 }
43 
decompressCheck(const void * srcBuff,size_t srcBuffSize)44 static void decompressCheck(const void* srcBuff, size_t srcBuffSize)
45 {
46     size_t const neededBuffSize = 20 * srcBuffSize;
47 
48     /* Allocate all buffers and contexts if not already allocated */
49     if (neededBuffSize > buffSize) {
50         free(rBuff);
51         buffSize = 0;
52 
53         rBuff = malloc(neededBuffSize);
54         if (!rBuff) {
55             fprintf(stderr, "not enough memory ! \n");
56             crash(1);
57         }
58         buffSize = neededBuffSize;
59     }
60     if (!dctx) {
61         size_t const workspaceSize = ZSTD_DCtxWorkspaceBound();
62         dws = malloc(workspaceSize);
63         if (!dws) {
64             fprintf(stderr, "not enough memory ! \n");
65             crash(1);
66         }
67         dctx = ZSTD_initDCtx(dws, workspaceSize);
68         if (!dctx) {
69             fprintf(stderr, "not enough memory ! \n");
70             crash(1);
71         }
72     }
73     ZSTD_decompressDCtx(dctx, rBuff, buffSize, srcBuff, srcBuffSize);
74 
75 #ifndef SKIP_FREE
76     free(dws); dws = NULL; dctx = NULL;
77     free(rBuff); rBuff = NULL;
78     buffSize = 0;
79 #endif
80 }
81 
LLVMFuzzerTestOneInput(const unsigned char * srcBuff,size_t srcBuffSize)82 int LLVMFuzzerTestOneInput(const unsigned char *srcBuff, size_t srcBuffSize) {
83   decompressCheck(srcBuff, srcBuffSize);
84   return 0;
85 }
86