From 70de7e0d9a95b7fcd7c105b06bd90fdf4e01f563 Mon Sep 17 00:00:00 2001 From: Max Moroz Date: Wed, 30 Dec 2020 10:10:23 -0800 Subject: [PATCH] [compiler-rt] FuzzedDataProvider: Add PickValueInArray for std::array This makes `PickValueInArray` work for `std::array` (C++11). I've also tested the C++17 `std::array` (with compiler-deduced template parameters) ``` Author: MarcoFalke ``` Reviewed By: Dor1s Differential Revision: https://reviews.llvm.org/D93412 --- compiler-rt/include/fuzzer/FuzzedDataProvider.h | 9 +++++++++ .../lib/fuzzer/tests/FuzzedDataProviderUnittest.cpp | 14 ++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/compiler-rt/include/fuzzer/FuzzedDataProvider.h b/compiler-rt/include/fuzzer/FuzzedDataProvider.h index 83bcd01..744a9d7 100644 --- a/compiler-rt/include/fuzzer/FuzzedDataProvider.h +++ b/compiler-rt/include/fuzzer/FuzzedDataProvider.h @@ -14,6 +14,7 @@ #define LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_ #include +#include #include #include #include @@ -71,6 +72,8 @@ class FuzzedDataProvider { // Returns a value from the given array. template T PickValueInArray(const T (&array)[size]); + template + T PickValueInArray(const std::array &array); template T PickValueInArray(std::initializer_list list); // Writes data to the given destination and returns number of bytes written. @@ -301,6 +304,12 @@ T FuzzedDataProvider::PickValueInArray(const T (&array)[size]) { return array[ConsumeIntegralInRange(0, size - 1)]; } +template +T FuzzedDataProvider::PickValueInArray(const std::array &array) { + static_assert(size > 0, "The array must be non empty."); + return array[ConsumeIntegralInRange(0, size - 1)]; +} + template T FuzzedDataProvider::PickValueInArray(std::initializer_list list) { // TODO(Dor1s): switch to static_assert once C++14 is allowed. diff --git a/compiler-rt/lib/fuzzer/tests/FuzzedDataProviderUnittest.cpp b/compiler-rt/lib/fuzzer/tests/FuzzedDataProviderUnittest.cpp index 99d9d8e..ea6774e 100644 --- a/compiler-rt/lib/fuzzer/tests/FuzzedDataProviderUnittest.cpp +++ b/compiler-rt/lib/fuzzer/tests/FuzzedDataProviderUnittest.cpp @@ -283,6 +283,20 @@ TEST(FuzzedDataProvider, ConsumeBool) { EXPECT_EQ(false, DataProv.ConsumeBool()); } +TEST(FuzzedDataProvider, PickValueInStdArray) { + FuzzedDataProvider DataProv(Data, sizeof(Data)); + const std::array Array = {1, 2, 3, 4, 5}; + EXPECT_EQ(5, DataProv.PickValueInArray(Array)); + EXPECT_EQ(2, DataProv.PickValueInArray(Array)); + EXPECT_EQ(2, DataProv.PickValueInArray(Array)); + EXPECT_EQ(3, DataProv.PickValueInArray(Array)); + EXPECT_EQ(3, DataProv.PickValueInArray(Array)); + EXPECT_EQ(3, DataProv.PickValueInArray(Array)); + EXPECT_EQ(1, DataProv.PickValueInArray(Array)); + EXPECT_EQ(3, DataProv.PickValueInArray(Array)); + EXPECT_EQ(2, DataProv.PickValueInArray(Array)); +} + TEST(FuzzedDataProvider, PickValueInArray) { FuzzedDataProvider DataProv(Data, sizeof(Data)); const int Array[] = {1, 2, 3, 4, 5}; -- 2.7.4