s3:tldap: simplify tldap_gensec_bind.h
[samba.git] / lib / fuzzing / fuzz_stable_sort.c
blobe2195cb049814a3fb986f9af35f2467e66d752e6
1 /*
2 Fuzzing for stable_sort
3 Copyright © Catalyst IT
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include "includes.h"
20 #include "fuzzing/fuzzing.h"
21 #include "talloc.h"
22 #include "util/stable_sort.h"
25 int LLVMFuzzerInitialize(int *argc, char ***argv)
27 return 0;
31 #define CMP_FN(type) static int cmp_ ## type (type *a, type *b) \
33 if (*a > *b) {\
34 return 1;\
36 if (*a < *b) {\
37 return -1;\
39 return 0;\
42 CMP_FN(uint8_t)
43 CMP_FN(uint16_t)
44 CMP_FN(uint32_t)
45 CMP_FN(uint64_t)
47 #define MAX_SIZE (1024 * 1024)
49 int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len)
51 TALLOC_CTX *mem_ctx = NULL;
52 samba_compare_fn_t fn;
53 size_t s, i;
54 uint8_t buf2[MAX_SIZE];
56 if (len < 1 || len > MAX_SIZE) {
57 return 0;
59 s = 1 << (buf[0] & 3);
60 if (s == 1) {
61 fn = (samba_compare_fn_t)cmp_uint8_t;
62 } else if (s == 2) {
63 fn = (samba_compare_fn_t)cmp_uint16_t;
64 } else if (s == 4) {
65 fn = (samba_compare_fn_t)cmp_uint32_t;
66 } else {
67 fn = (samba_compare_fn_t)cmp_uint64_t;
69 buf++;
70 len--;
71 len -= len & (s - 1);
73 mem_ctx = talloc_new(NULL);
74 memcpy(buf2, buf, len);
76 stable_sort_talloc(mem_ctx, buf2, len / s, s, fn);
78 talloc_free(mem_ctx);
80 for (i = s; i < len; i += s) {
81 int c = fn(&buf2[i - s], &buf2[i]);
82 if (c > 0) {
83 abort();
87 return 0;