summaryrefslogtreecommitdiff
path: root/libc/fuzzing/stdlib
diff options
context:
space:
mode:
authorSiva Chandra Reddy <sivachandra@google.com>2021-09-22 21:31:50 +0000
committerSiva Chandra Reddy <sivachandra@google.com>2021-09-24 19:22:45 +0000
commit5eb6b8272931473f3b279db5d2c0006993fda21a (patch)
treea8bd64cb8c58e25dd6e8cc3b58fdb7c2a95e92d0 /libc/fuzzing/stdlib
parentebe06910ce2623f525e458a91d7e5a1858163226 (diff)
[libc] Add an implementation of qsort.
A fuzzer for qsort has also been added. Reviewed By: michaelrj Differential Revision: https://reviews.llvm.org/D110382
Diffstat (limited to 'libc/fuzzing/stdlib')
-rw-r--r--libc/fuzzing/stdlib/CMakeLists.txt8
-rw-r--r--libc/fuzzing/stdlib/qsort_fuzz.cpp46
2 files changed, 54 insertions, 0 deletions
diff --git a/libc/fuzzing/stdlib/CMakeLists.txt b/libc/fuzzing/stdlib/CMakeLists.txt
new file mode 100644
index 000000000000..db827f57075f
--- /dev/null
+++ b/libc/fuzzing/stdlib/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_libc_fuzzer(
+ qsort_fuzz
+ SRCS
+ qsort_fuzz.cpp
+ DEPENDS
+ libc.src.stdlib.qsort
+)
+
diff --git a/libc/fuzzing/stdlib/qsort_fuzz.cpp b/libc/fuzzing/stdlib/qsort_fuzz.cpp
new file mode 100644
index 000000000000..dbbc8e96f924
--- /dev/null
+++ b/libc/fuzzing/stdlib/qsort_fuzz.cpp
@@ -0,0 +1,46 @@
+//===-- qsort_fuzz.cpp ----------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// Fuzzing test for llvm-libc qsort implementation.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/stdlib/qsort.h"
+#include <stdint.h>
+
+static int int_compare(const void *l, const void *r) {
+ int li = *reinterpret_cast<const int *>(l);
+ int ri = *reinterpret_cast<const int *>(r);
+ if (li == ri)
+ return 0;
+ else if (li > ri)
+ return 1;
+ else
+ return -1;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+ const size_t array_size = size / sizeof(int);
+ if (array_size == 0)
+ return 0;
+
+ int *array = new int[array_size];
+ const int *data_as_int = reinterpret_cast<const int *>(data);
+ for (size_t i = 0; i < array_size; ++i)
+ array[i] = data_as_int[i];
+
+ __llvm_libc::qsort(array, array_size, sizeof(int), int_compare);
+
+ for (size_t i = 0; i < array_size - 1; ++i) {
+ if (array[i] > array[i + 1])
+ __builtin_trap();
+ }
+
+ delete[] array;
+ return 0;
+}