| 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(pa: a, pb: 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(format: "%s\"" , msg); |
| 44 | for (size_t i = 0; i < size; ++i) |
| 45 | printf(format: "\\x%02x" , (uint8_t)buffer[i]); |
| 46 | printf(format: "\"\n" ); |
| 47 | }; |
| 48 | printf(format: "count : %zu\n" , count); |
| 49 | print("a : " , a, count); |
| 50 | print("b : " , b, count); |
| 51 | printf(format: "expected : %d\n" , reference); |
| 52 | printf(format: "actual : %d\n" , actual); |
| 53 | __builtin_trap(); |
| 54 | } |
| 55 | |