File: fuzz_test.c

package info (click to toggle)
libcbor 0.5.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 1,176 kB
  • sloc: ansic: 7,131; makefile: 154; sh: 71; python: 54; ruby: 17; cpp: 6
file content (101 lines) | stat: -rw-r--r-- 1,914 bytes parent folder | download
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
 * Copyright (c) 2014-2017 Pavel Kalvoda <me@pavelkalvoda.com>
 *
 * libcbor is free software; you can redistribute it and/or modify
 * it under the terms of the MIT license. See LICENSE for details.
 */

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <stdio.h>
#include "cbor.h"
#include <inttypes.h>
#include <stdlib.h>
#include <time.h>

#ifdef HUGE_FUZZ
	#define ROUNDS 65536ULL
	#define MAXLEN 131072ULL
#else
	#define ROUNDS 256ULL
	#define MAXLEN 2048ULL
#endif

#ifdef PRINT_FUZZ
static void printmem(const unsigned char * ptr, size_t length)
{
	for (size_t i = 0; i < length; i++)
		printf("%02X", ptr[i]);
	printf("\n");
}
#endif

unsigned seed;

#if CBOR_CUSTOM_ALLOC
void *mock_malloc(size_t size)
{
	if (size > (1 << 19))
		return NULL;
	else
		return malloc(size);
}
#endif

static void run_round()
{
	cbor_item_t *item;
	struct cbor_load_result res;

	size_t length = rand() % MAXLEN + 1;
	unsigned char * data = malloc(length);
	for (size_t i = 0; i < length; i++) {
		data[i] = rand() % 0xFF;
	}

#ifdef PRINT_FUZZ
	printmem(data, length);
#endif

	item = cbor_load(data, length, &res);

	if (res.error.code == CBOR_ERR_NONE)
		cbor_decref(&item);
	/* Otherwise there should be nothing left behind by the decoder */

	free(data);
}

static void fuzz(void **state)
{

#if CBOR_CUSTOM_ALLOC
	cbor_set_allocs(mock_malloc, realloc, free);
#endif
	printf(
		"Fuzzing %llu rounds of up to %llu bytes with seed %u\n",
		ROUNDS,
		MAXLEN,
		seed);
	srand(seed);

	for (size_t i = 0; i < ROUNDS; i++)
		run_round();

	printf("Successfully fuzzed through %llu kB of data\n", (ROUNDS * MAXLEN) / 1024);
}

int main(int argc, char * argv[])
{
	if (argc > 1)
		seed = (unsigned) strtoul(argv[1], NULL, 10);
	else
		seed = (unsigned) time(NULL);

	const struct CMUnitTest tests[] = {
		cmocka_unit_test(fuzz)
	};
	return cmocka_run_group_tests(tests, NULL, NULL);
}