xref: /netbsd-src/external/bsd/zstd/dist/tests/fuzz/fuzz_helpers.c (revision 3117ece4fc4a4ca4489ba793710b60b0d26bab6c)
1*3117ece4Schristos /*
2*3117ece4Schristos  * Copyright (c) Meta Platforms, Inc. and affiliates.
3*3117ece4Schristos  * All rights reserved.
4*3117ece4Schristos  *
5*3117ece4Schristos  * This source code is licensed under both the BSD-style license (found in the
6*3117ece4Schristos  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*3117ece4Schristos  * in the COPYING file in the root directory of this source tree).
8*3117ece4Schristos  * You may select, at your option, one of the above-listed licenses.
9*3117ece4Schristos  */
10*3117ece4Schristos #include "fuzz_helpers.h"
11*3117ece4Schristos 
12*3117ece4Schristos #include <stddef.h>
13*3117ece4Schristos #include <stdlib.h>
14*3117ece4Schristos #include <string.h>
15*3117ece4Schristos 
16*3117ece4Schristos void* FUZZ_malloc(size_t size)
17*3117ece4Schristos {
18*3117ece4Schristos     if (size > 0) {
19*3117ece4Schristos         void* const mem = malloc(size);
20*3117ece4Schristos         FUZZ_ASSERT(mem);
21*3117ece4Schristos         return mem;
22*3117ece4Schristos     }
23*3117ece4Schristos     return NULL;
24*3117ece4Schristos }
25*3117ece4Schristos 
26*3117ece4Schristos void* FUZZ_malloc_rand(size_t size, FUZZ_dataProducer_t *producer)
27*3117ece4Schristos {
28*3117ece4Schristos     if (size > 0) {
29*3117ece4Schristos         void* const mem = malloc(size);
30*3117ece4Schristos         FUZZ_ASSERT(mem);
31*3117ece4Schristos         return mem;
32*3117ece4Schristos     } else {
33*3117ece4Schristos         uintptr_t ptr = 0;
34*3117ece4Schristos         /* Add +- 1M 50% of the time */
35*3117ece4Schristos         if (FUZZ_dataProducer_uint32Range(producer, 0, 1))
36*3117ece4Schristos             FUZZ_dataProducer_int32Range(producer, -1000000, 1000000);
37*3117ece4Schristos         return (void*)ptr;
38*3117ece4Schristos     }
39*3117ece4Schristos 
40*3117ece4Schristos }
41*3117ece4Schristos 
42*3117ece4Schristos int FUZZ_memcmp(void const* lhs, void const* rhs, size_t size)
43*3117ece4Schristos {
44*3117ece4Schristos     if (size == 0) {
45*3117ece4Schristos         return 0;
46*3117ece4Schristos     }
47*3117ece4Schristos     return memcmp(lhs, rhs, size);
48*3117ece4Schristos }
49