File: fuzz_test.c

package info (click to toggle)
mysql-8.0 8.0.43-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,904 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,184; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,196; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (78 lines) | stat: -rw-r--r-- 1,780 bytes parent folder | download | duplicates (3)
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
/*
 * Copyright (c) 2014-2020 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 <time.h>
#include "assertions.h"
#include "cbor.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;

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

static void run_round(void) {
  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 **_CBOR_UNUSED(_state)) {
  cbor_set_allocs(mock_malloc, realloc, free);
  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);
}