1// Check interceptor.
2// RUN: %clangxx -O0 %s -o %t && %run %t 2>&1 | FileCheck %s
3
4// Inlined bsearch works even without interceptors.
5// RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
6
7#include <stdio.h>
8#include <stdlib.h>
9
10static int arr1[] = {8, 7, 6, 5, 4, 3, 2, 1, 0};
11static int arr2[] = {10, 1, 1, 3, 4, 6, 7, 7};
12
13#define array_size(x) (sizeof(x) / sizeof(x[0]))
14
15static int cmp_ints(const void *a, const void *b) {
16 return *(const int *)b - *(const int *)a;
17}
18
19static int cmp_pos(const void *a, const void *b) {
20 const int *ap =
21 (const int *)bsearch(key: a, base: arr1, array_size(arr1), size: sizeof(int), compar: &cmp_ints);
22 if (!ap)
23 ap = arr1 + array_size(arr1);
24 const int *bp =
25 (const int *)bsearch(key: b, base: arr1, array_size(arr1), size: sizeof(int), compar: &cmp_ints);
26 if (!bp)
27 bp = arr1 + array_size(arr1);
28 return bp - ap;
29}
30
31int main() {
32 // Simple bsearch.
33 for (int i = 0; i < 10; ++i) {
34 const void *r =
35 bsearch(key: &i, base: arr1, array_size(arr1), size: sizeof(arr1[0]), compar: &cmp_ints);
36 if (!r)
37 printf(format: " null");
38 else
39 printf(format: " %d", *(const int *)r);
40 }
41 printf(format: "\n");
42 // CHECK: 0 1 2 3 4 5 6 7 8 null
43
44 // Nested bsearch.
45 for (int i = 0; i < 10; ++i) {
46 const void *r =
47 bsearch(key: &i, base: arr2, array_size(arr2), size: sizeof(arr2[0]), compar: &cmp_pos);
48 if (!r)
49 printf(format: " null");
50 else
51 printf(format: " %d", *(const int *)r);
52 }
53 printf(format: "\n");
54 // CHECK: null 1 null 3 4 null 6 7 null 10
55}
56

source code of compiler-rt/test/sanitizer_common/TestCases/Posix/bsearch.cpp