xref: /llvm-project/compiler-rt/test/fuzzer/CustomAllocator.cpp (revision 831ae45e3dc609e43ba561af07670a8fe47461ef)
1*831ae45eSDokyung Song // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2*831ae45eSDokyung Song // See https://llvm.org/LICENSE.txt for license information.
3*831ae45eSDokyung Song // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4*831ae45eSDokyung Song 
5*831ae45eSDokyung Song // Test whether calling certain libFuzzer's interceptors inside allocators
6*831ae45eSDokyung Song // does not cause an assertion failure.
7*831ae45eSDokyung Song #include <assert.h>
8*831ae45eSDokyung Song #include <cstddef>
9*831ae45eSDokyung Song #include <cstdint>
10*831ae45eSDokyung Song #include <cstdlib>
11*831ae45eSDokyung Song #include <cstring>
12*831ae45eSDokyung Song #include <iostream>
13*831ae45eSDokyung Song #include <malloc.h>
14*831ae45eSDokyung Song 
15*831ae45eSDokyung Song static const char *buf1 = "aaaa";
16*831ae45eSDokyung Song static const char *buf2 = "bbbb";
17*831ae45eSDokyung Song 
callFuzzerInterceptors(const char * prefix)18*831ae45eSDokyung Song static void callFuzzerInterceptors(const char *prefix) {
19*831ae45eSDokyung Song   int memcmp_result = memcmp(buf1, buf2, 4);
20*831ae45eSDokyung Song   if (memcmp_result != 0) {
21*831ae45eSDokyung Song     fprintf(stderr, "%s-MEMCMP\n", prefix);
22*831ae45eSDokyung Song   }
23*831ae45eSDokyung Song   int strncmp_result = strncmp(buf1, buf2, 4);
24*831ae45eSDokyung Song   if (strncmp_result != 0) {
25*831ae45eSDokyung Song     fprintf(stderr, "%s-STRNCMP\n", prefix);
26*831ae45eSDokyung Song   }
27*831ae45eSDokyung Song   int strcmp_result = strcmp(buf1, buf2);
28*831ae45eSDokyung Song   if (strcmp_result != 0) {
29*831ae45eSDokyung Song     fprintf(stderr, "%s-STRCMP\n", prefix);
30*831ae45eSDokyung Song   }
31*831ae45eSDokyung Song   const char *strstr_result = strstr(buf1, buf2);
32*831ae45eSDokyung Song   if (strstr_result == nullptr) {
33*831ae45eSDokyung Song     fprintf(stderr, "%s-STRSTR\n", prefix);
34*831ae45eSDokyung Song   }
35*831ae45eSDokyung Song }
36*831ae45eSDokyung Song 
37*831ae45eSDokyung Song extern "C" void *__libc_calloc(size_t, size_t);
38*831ae45eSDokyung Song 
calloc(size_t n,size_t elem_size)39*831ae45eSDokyung Song extern "C" void *calloc(size_t n, size_t elem_size) {
40*831ae45eSDokyung Song   static bool CalledOnce = false;
41*831ae45eSDokyung Song   if (!CalledOnce) {
42*831ae45eSDokyung Song     callFuzzerInterceptors("CALLOC");
43*831ae45eSDokyung Song     CalledOnce = true;
44*831ae45eSDokyung Song   }
45*831ae45eSDokyung Song   return __libc_calloc(n, elem_size);
46*831ae45eSDokyung Song }
47