xref: /freebsd/contrib/libcbor/test/fuzz_test.c (revision e9e8876a4d6afc1ad5315faaa191b25121a813d7)
1 /*
2  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3  *
4  * libcbor is free software; you can redistribute it and/or modify
5  * it under the terms of the MIT license. See LICENSE for details.
6  */
7 
8 #include <setjmp.h>
9 #include <stdarg.h>
10 #include <stddef.h>
11 
12 #include <cmocka.h>
13 
14 #include <time.h>
15 #include "cbor.h"
16 
17 #ifdef HUGE_FUZZ
18 #define ROUNDS 65536ULL
19 #define MAXLEN 131072ULL
20 #else
21 #define ROUNDS 256ULL
22 #define MAXLEN 2048ULL
23 #endif
24 
25 #ifdef PRINT_FUZZ
26 static void printmem(const unsigned char *ptr, size_t length) {
27   for (size_t i = 0; i < length; i++) printf("%02X", ptr[i]);
28   printf("\n");
29 }
30 #endif
31 
32 unsigned seed;
33 
34 #if CBOR_CUSTOM_ALLOC
35 void *mock_malloc(size_t size) {
36   if (size > (1 << 19))
37     return NULL;
38   else
39     return malloc(size);
40 }
41 #endif
42 
43 static void run_round() {
44   cbor_item_t *item;
45   struct cbor_load_result res;
46 
47   size_t length = rand() % MAXLEN + 1;
48   unsigned char *data = malloc(length);
49   for (size_t i = 0; i < length; i++) {
50     data[i] = rand() % 0xFF;
51   }
52 
53 #ifdef PRINT_FUZZ
54   printmem(data, length);
55 #endif
56 
57   item = cbor_load(data, length, &res);
58 
59   if (res.error.code == CBOR_ERR_NONE) cbor_decref(&item);
60   /* Otherwise there should be nothing left behind by the decoder */
61 
62   free(data);
63 }
64 
65 static void fuzz(void **state) {
66 #if CBOR_CUSTOM_ALLOC
67   cbor_set_allocs(mock_malloc, realloc, free);
68 #endif
69   printf("Fuzzing %llu rounds of up to %llu bytes with seed %u\n", ROUNDS,
70          MAXLEN, seed);
71   srand(seed);
72 
73   for (size_t i = 0; i < ROUNDS; i++) run_round();
74 
75   printf("Successfully fuzzed through %llu kB of data\n",
76          (ROUNDS * MAXLEN) / 1024);
77 }
78 
79 int main(int argc, char *argv[]) {
80   if (argc > 1)
81     seed = (unsigned)strtoul(argv[1], NULL, 10);
82   else
83     seed = (unsigned)time(NULL);
84 
85   const struct CMUnitTest tests[] = {cmocka_unit_test(fuzz)};
86   return cmocka_run_group_tests(tests, NULL, NULL);
87 }
88