xref: /llvm-project/libc/fuzzing/string/bcmp_fuzz.cpp (revision 431ea2d076f8a5ca35b2c293dd5d62f5ce083f45)
1 //===-- bcmp_fuzz.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// Fuzzing test for llvm-libc bcmp implementation.
10 ///
11 //===----------------------------------------------------------------------===//
12 #include "src/strings/bcmp.h"
13 #include <stddef.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <string.h>
17 
18 static int reference_bcmp(const void *pa, const void *pb, size_t count)
19     __attribute__((no_builtin)) {
20   const auto *a = reinterpret_cast<const unsigned char *>(pa);
21   const auto *b = reinterpret_cast<const unsigned char *>(pb);
22   for (size_t i = 0; i < count; ++i, ++a, ++b)
23     if (*a != *b)
24       return 1;
25   return 0;
26 }
27 
28 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
29   const auto normalize = [](int value) -> int {
30     if (value == 0)
31       return 0;
32     return 1;
33   };
34   // We ignore the last byte is size is odd.
35   const auto count = size / 2;
36   const char *a = reinterpret_cast<const char *>(data);
37   const char *b = reinterpret_cast<const char *>(data) + count;
38   const int actual = LIBC_NAMESPACE::bcmp(a, b, count);
39   const int reference = reference_bcmp(a, b, count);
40   if (normalize(actual) == normalize(reference))
41     return 0;
42   const auto print = [](const char *msg, const char *buffer, size_t size) {
43     printf("%s\"", msg);
44     for (size_t i = 0; i < size; ++i)
45       printf("\\x%02x", (uint8_t)buffer[i]);
46     printf("\"\n");
47   };
48   printf("count    : %zu\n", count);
49   print("a        : ", a, count);
50   print("b        : ", b, count);
51   printf("expected : %d\n", reference);
52   printf("actual   : %d\n", actual);
53   __builtin_trap();
54 }
55