1//===-- memcmp_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 memcmp implementation.
10///
11//===----------------------------------------------------------------------===//
12#include "src/string/memcmp.h"
13#include <stddef.h>
14#include <stdint.h>
15#include <stdio.h>
16#include <string.h>
17
18static int reference_memcmp(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 else if (*a > *b)
26 return 1;
27 }
28 return 0;
29}
30
31extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
32 const auto sign = [](int value) -> int {
33 if (value < 0)
34 return -1;
35 if (value > 0)
36 return 1;
37 return 0;
38 };
39 // We ignore the last byte is size is odd.
40 const auto count = size / 2;
41 const char *a = reinterpret_cast<const char *>(data);
42 const char *b = reinterpret_cast<const char *>(data) + count;
43 const int actual = LIBC_NAMESPACE::memcmp(lhs: a, rhs: b, count);
44 const int reference = reference_memcmp(pa: a, pb: b, count);
45 if (sign(actual) == sign(reference))
46 return 0;
47 const auto print = [](const char *msg, const char *buffer, size_t size) {
48 printf(format: "%s\"", msg);
49 for (size_t i = 0; i < size; ++i)
50 printf(format: "\\x%02x", (uint8_t)buffer[i]);
51 printf(format: "\"\n");
52 };
53 printf(format: "count : %zu\n", count);
54 print("a : ", a, count);
55 print("b : ", b, count);
56 printf(format: "expected : %d\n", reference);
57 printf(format: "actual : %d\n", actual);
58 __builtin_trap();
59}
60

source code of libc/fuzzing/string/memcmp_fuzz.cpp