1 //===-- strcmp_fuzz.cpp ---------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 /// Fuzzing test for llvm-libc strcmp implementation.
11 //===----------------------------------------------------------------------===//
12 #include "src/string/strcmp.h"
16 // The general structure is to take the value of the first byte, set size1 to
17 // that value, and add the null terminator. size2 will then contain the rest of
19 // For example, with inputs (data={2, 6, 4, 8, 0}, size=5):
21 // data1: {2, 6} + '\0' = {2, 6, '\0'}
22 // size2: size - size1 = 3
23 // data2: {4, 8, '\0'}
24 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data
, size_t size
) {
25 // Verify the size is at least 1 and the data is null terminated.
26 if (!size
|| data
[size
- 1] != '\0')
29 const size_t size1
= (data
[0] <= size
? data
[0] : size
);
30 const size_t size2
= size
- size1
;
32 // The first size will always be at least 1 since
33 // we need to append the null terminator. The second size
34 // needs to be checked since it must also contain the null
39 // Copy the data into new containers.
40 // Add one to data1 for null terminator.
41 uint8_t *data1
= new uint8_t[size1
+ 1];
42 uint8_t *data2
= new uint8_t[size2
];
47 for (i
= 0; i
< size1
; ++i
)
49 data1
[size1
] = '\0'; // Add null terminator to data1.
51 for (size_t j
= 0; j
< size2
; ++j
)
54 const char *s1
= reinterpret_cast<const char *>(data1
);
55 const char *s2
= reinterpret_cast<const char *>(data2
);
57 // Iterate until a null terminator is hit or the character comparison is
59 while (s1
[k
] && s2
[k
] && s1
[k
] == s2
[k
])
62 const unsigned char ch1
= static_cast<unsigned char>(s1
[k
]);
63 const unsigned char ch2
= static_cast<unsigned char>(s2
[k
]);
64 // The expected result should be the difference between the first non-equal
65 // characters of s1 and s2. If all characters are equal, the expected result
66 // should be '\0' - '\0' = 0.
67 if (LIBC_NAMESPACE::strcmp(s1
, s2
) != ch1
- ch2
)
70 // Verify reversed operands. This should be the negated value of the previous
71 // result, except of course if the previous result was zero.
72 if (LIBC_NAMESPACE::strcmp(s2
, s1
) != ch2
- ch1
)