xref: /freebsd-src/contrib/llvm-project/compiler-rt/include/fuzzer/FuzzedDataProvider.h (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
168d75effSDimitry Andric //===- FuzzedDataProvider.h - Utility header for fuzz targets ---*- C++ -* ===//
268d75effSDimitry Andric //
368d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
468d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
568d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
668d75effSDimitry Andric //
768d75effSDimitry Andric //===----------------------------------------------------------------------===//
868d75effSDimitry Andric // A single header library providing an utility class to break up an array of
968d75effSDimitry Andric // bytes. Whenever run on the same input, provides the same output, as long as
1068d75effSDimitry Andric // its methods are called in the same order, with the same arguments.
1168d75effSDimitry Andric //===----------------------------------------------------------------------===//
1268d75effSDimitry Andric 
1368d75effSDimitry Andric #ifndef LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
1468d75effSDimitry Andric #define LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
1568d75effSDimitry Andric 
1668d75effSDimitry Andric #include <algorithm>
17e8d8bef9SDimitry Andric #include <array>
1868d75effSDimitry Andric #include <climits>
1968d75effSDimitry Andric #include <cstddef>
2068d75effSDimitry Andric #include <cstdint>
2168d75effSDimitry Andric #include <cstring>
2268d75effSDimitry Andric #include <initializer_list>
23fe6060f1SDimitry Andric #include <limits>
2468d75effSDimitry Andric #include <string>
2568d75effSDimitry Andric #include <type_traits>
2668d75effSDimitry Andric #include <utility>
2768d75effSDimitry Andric #include <vector>
2868d75effSDimitry Andric 
2968d75effSDimitry Andric // In addition to the comments below, the API is also briefly documented at
3068d75effSDimitry Andric // https://github.com/google/fuzzing/blob/master/docs/split-inputs.md#fuzzed-data-provider
3168d75effSDimitry Andric class FuzzedDataProvider {
3268d75effSDimitry Andric  public:
3368d75effSDimitry Andric   // |data| is an array of length |size| that the FuzzedDataProvider wraps to
3468d75effSDimitry Andric   // provide more granular access. |data| must outlive the FuzzedDataProvider.
FuzzedDataProvider(const uint8_t * data,size_t size)3568d75effSDimitry Andric   FuzzedDataProvider(const uint8_t *data, size_t size)
3668d75effSDimitry Andric       : data_ptr_(data), remaining_bytes_(size) {}
3768d75effSDimitry Andric   ~FuzzedDataProvider() = default;
3868d75effSDimitry Andric 
395ffd83dbSDimitry Andric   // See the implementation below (after the class definition) for more verbose
405ffd83dbSDimitry Andric   // comments for each of the methods.
415ffd83dbSDimitry Andric 
425ffd83dbSDimitry Andric   // Methods returning std::vector of bytes. These are the most popular choice
435ffd83dbSDimitry Andric   // when splitting fuzzing input into pieces, as every piece is put into a
445ffd83dbSDimitry Andric   // separate buffer (i.e. ASan would catch any under-/overflow) and the memory
455ffd83dbSDimitry Andric   // will be released automatically.
465ffd83dbSDimitry Andric   template <typename T> std::vector<T> ConsumeBytes(size_t num_bytes);
475ffd83dbSDimitry Andric   template <typename T>
485ffd83dbSDimitry Andric   std::vector<T> ConsumeBytesWithTerminator(size_t num_bytes, T terminator = 0);
495ffd83dbSDimitry Andric   template <typename T> std::vector<T> ConsumeRemainingBytes();
505ffd83dbSDimitry Andric 
515ffd83dbSDimitry Andric   // Methods returning strings. Use only when you need a std::string or a null
525ffd83dbSDimitry Andric   // terminated C-string. Otherwise, prefer the methods returning std::vector.
535ffd83dbSDimitry Andric   std::string ConsumeBytesAsString(size_t num_bytes);
545ffd83dbSDimitry Andric   std::string ConsumeRandomLengthString(size_t max_length);
555ffd83dbSDimitry Andric   std::string ConsumeRandomLengthString();
565ffd83dbSDimitry Andric   std::string ConsumeRemainingBytesAsString();
575ffd83dbSDimitry Andric 
585ffd83dbSDimitry Andric   // Methods returning integer values.
595ffd83dbSDimitry Andric   template <typename T> T ConsumeIntegral();
605ffd83dbSDimitry Andric   template <typename T> T ConsumeIntegralInRange(T min, T max);
615ffd83dbSDimitry Andric 
625ffd83dbSDimitry Andric   // Methods returning floating point values.
635ffd83dbSDimitry Andric   template <typename T> T ConsumeFloatingPoint();
645ffd83dbSDimitry Andric   template <typename T> T ConsumeFloatingPointInRange(T min, T max);
655ffd83dbSDimitry Andric 
665ffd83dbSDimitry Andric   // 0 <= return value <= 1.
675ffd83dbSDimitry Andric   template <typename T> T ConsumeProbability();
685ffd83dbSDimitry Andric 
695ffd83dbSDimitry Andric   bool ConsumeBool();
705ffd83dbSDimitry Andric 
715ffd83dbSDimitry Andric   // Returns a value chosen from the given enum.
725ffd83dbSDimitry Andric   template <typename T> T ConsumeEnum();
735ffd83dbSDimitry Andric 
745ffd83dbSDimitry Andric   // Returns a value from the given array.
755ffd83dbSDimitry Andric   template <typename T, size_t size> T PickValueInArray(const T (&array)[size]);
76e8d8bef9SDimitry Andric   template <typename T, size_t size>
77e8d8bef9SDimitry Andric   T PickValueInArray(const std::array<T, size> &array);
785ffd83dbSDimitry Andric   template <typename T> T PickValueInArray(std::initializer_list<const T> list);
795ffd83dbSDimitry Andric 
805ffd83dbSDimitry Andric   // Writes data to the given destination and returns number of bytes written.
815ffd83dbSDimitry Andric   size_t ConsumeData(void *destination, size_t num_bytes);
825ffd83dbSDimitry Andric 
835ffd83dbSDimitry Andric   // Reports the remaining bytes available for fuzzed input.
remaining_bytes()845ffd83dbSDimitry Andric   size_t remaining_bytes() { return remaining_bytes_; }
855ffd83dbSDimitry Andric 
865ffd83dbSDimitry Andric  private:
875ffd83dbSDimitry Andric   FuzzedDataProvider(const FuzzedDataProvider &) = delete;
885ffd83dbSDimitry Andric   FuzzedDataProvider &operator=(const FuzzedDataProvider &) = delete;
895ffd83dbSDimitry Andric 
905ffd83dbSDimitry Andric   void CopyAndAdvance(void *destination, size_t num_bytes);
915ffd83dbSDimitry Andric 
925ffd83dbSDimitry Andric   void Advance(size_t num_bytes);
935ffd83dbSDimitry Andric 
945ffd83dbSDimitry Andric   template <typename T>
955ffd83dbSDimitry Andric   std::vector<T> ConsumeBytes(size_t size, size_t num_bytes);
965ffd83dbSDimitry Andric 
975ffd83dbSDimitry Andric   template <typename TS, typename TU> TS ConvertUnsignedToSigned(TU value);
985ffd83dbSDimitry Andric 
995ffd83dbSDimitry Andric   const uint8_t *data_ptr_;
1005ffd83dbSDimitry Andric   size_t remaining_bytes_;
1015ffd83dbSDimitry Andric };
1025ffd83dbSDimitry Andric 
10368d75effSDimitry Andric // Returns a std::vector containing |num_bytes| of input data. If fewer than
10468d75effSDimitry Andric // |num_bytes| of data remain, returns a shorter std::vector containing all
10568d75effSDimitry Andric // of the data that's left. Can be used with any byte sized type, such as
10668d75effSDimitry Andric // char, unsigned char, uint8_t, etc.
1075ffd83dbSDimitry Andric template <typename T>
ConsumeBytes(size_t num_bytes)1085ffd83dbSDimitry Andric std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t num_bytes) {
10968d75effSDimitry Andric   num_bytes = std::min(num_bytes, remaining_bytes_);
11068d75effSDimitry Andric   return ConsumeBytes<T>(num_bytes, num_bytes);
11168d75effSDimitry Andric }
11268d75effSDimitry Andric 
11368d75effSDimitry Andric // Similar to |ConsumeBytes|, but also appends the terminator value at the end
11468d75effSDimitry Andric // of the resulting vector. Useful, when a mutable null-terminated C-string is
11568d75effSDimitry Andric // needed, for example. But that is a rare case. Better avoid it, if possible,
11668d75effSDimitry Andric // and prefer using |ConsumeBytes| or |ConsumeBytesAsString| methods.
11768d75effSDimitry Andric template <typename T>
ConsumeBytesWithTerminator(size_t num_bytes,T terminator)1185ffd83dbSDimitry Andric std::vector<T> FuzzedDataProvider::ConsumeBytesWithTerminator(size_t num_bytes,
1195ffd83dbSDimitry Andric                                                               T terminator) {
12068d75effSDimitry Andric   num_bytes = std::min(num_bytes, remaining_bytes_);
12168d75effSDimitry Andric   std::vector<T> result = ConsumeBytes<T>(num_bytes + 1, num_bytes);
12268d75effSDimitry Andric   result.back() = terminator;
12368d75effSDimitry Andric   return result;
12468d75effSDimitry Andric }
12568d75effSDimitry Andric 
1265ffd83dbSDimitry Andric // Returns a std::vector containing all remaining bytes of the input data.
1275ffd83dbSDimitry Andric template <typename T>
ConsumeRemainingBytes()1285ffd83dbSDimitry Andric std::vector<T> FuzzedDataProvider::ConsumeRemainingBytes() {
1295ffd83dbSDimitry Andric   return ConsumeBytes<T>(remaining_bytes_);
1305ffd83dbSDimitry Andric }
1315ffd83dbSDimitry Andric 
13268d75effSDimitry Andric // Returns a std::string containing |num_bytes| of input data. Using this and
13368d75effSDimitry Andric // |.c_str()| on the resulting string is the best way to get an immutable
13468d75effSDimitry Andric // null-terminated C string. If fewer than |num_bytes| of data remain, returns
13568d75effSDimitry Andric // a shorter std::string containing all of the data that's left.
ConsumeBytesAsString(size_t num_bytes)1365ffd83dbSDimitry Andric inline std::string FuzzedDataProvider::ConsumeBytesAsString(size_t num_bytes) {
13768d75effSDimitry Andric   static_assert(sizeof(std::string::value_type) == sizeof(uint8_t),
13868d75effSDimitry Andric                 "ConsumeBytesAsString cannot convert the data to a string.");
13968d75effSDimitry Andric 
14068d75effSDimitry Andric   num_bytes = std::min(num_bytes, remaining_bytes_);
14168d75effSDimitry Andric   std::string result(
1425ffd83dbSDimitry Andric       reinterpret_cast<const std::string::value_type *>(data_ptr_), num_bytes);
14368d75effSDimitry Andric   Advance(num_bytes);
14468d75effSDimitry Andric   return result;
14568d75effSDimitry Andric }
14668d75effSDimitry Andric 
1475ffd83dbSDimitry Andric // Returns a std::string of length from 0 to |max_length|. When it runs out of
1485ffd83dbSDimitry Andric // input data, returns what remains of the input. Designed to be more stable
1495ffd83dbSDimitry Andric // with respect to a fuzzer inserting characters than just picking a random
1505ffd83dbSDimitry Andric // length and then consuming that many bytes with |ConsumeBytes|.
1515ffd83dbSDimitry Andric inline std::string
ConsumeRandomLengthString(size_t max_length)1525ffd83dbSDimitry Andric FuzzedDataProvider::ConsumeRandomLengthString(size_t max_length) {
1535ffd83dbSDimitry Andric   // Reads bytes from the start of |data_ptr_|. Maps "\\" to "\", and maps "\"
1545ffd83dbSDimitry Andric   // followed by anything else to the end of the string. As a result of this
1555ffd83dbSDimitry Andric   // logic, a fuzzer can insert characters into the string, and the string
1565ffd83dbSDimitry Andric   // will be lengthened to include those new characters, resulting in a more
1575ffd83dbSDimitry Andric   // stable fuzzer than picking the length of a string independently from
1585ffd83dbSDimitry Andric   // picking its contents.
1595ffd83dbSDimitry Andric   std::string result;
1605ffd83dbSDimitry Andric 
161*5f757f3fSDimitry Andric   // Reserve the anticipated capacity to prevent several reallocations.
1625ffd83dbSDimitry Andric   result.reserve(std::min(max_length, remaining_bytes_));
1635ffd83dbSDimitry Andric   for (size_t i = 0; i < max_length && remaining_bytes_ != 0; ++i) {
1645ffd83dbSDimitry Andric     char next = ConvertUnsignedToSigned<char>(data_ptr_[0]);
1655ffd83dbSDimitry Andric     Advance(1);
1665ffd83dbSDimitry Andric     if (next == '\\' && remaining_bytes_ != 0) {
1675ffd83dbSDimitry Andric       next = ConvertUnsignedToSigned<char>(data_ptr_[0]);
1685ffd83dbSDimitry Andric       Advance(1);
1695ffd83dbSDimitry Andric       if (next != '\\')
1705ffd83dbSDimitry Andric         break;
1715ffd83dbSDimitry Andric     }
1725ffd83dbSDimitry Andric     result += next;
1735ffd83dbSDimitry Andric   }
1745ffd83dbSDimitry Andric 
1755ffd83dbSDimitry Andric   result.shrink_to_fit();
1765ffd83dbSDimitry Andric   return result;
1775ffd83dbSDimitry Andric }
1785ffd83dbSDimitry Andric 
1795ffd83dbSDimitry Andric // Returns a std::string of length from 0 to |remaining_bytes_|.
ConsumeRandomLengthString()1805ffd83dbSDimitry Andric inline std::string FuzzedDataProvider::ConsumeRandomLengthString() {
1815ffd83dbSDimitry Andric   return ConsumeRandomLengthString(remaining_bytes_);
1825ffd83dbSDimitry Andric }
1835ffd83dbSDimitry Andric 
1845ffd83dbSDimitry Andric // Returns a std::string containing all remaining bytes of the input data.
1855ffd83dbSDimitry Andric // Prefer using |ConsumeRemainingBytes| unless you actually need a std::string
1865ffd83dbSDimitry Andric // object.
ConsumeRemainingBytesAsString()1875ffd83dbSDimitry Andric inline std::string FuzzedDataProvider::ConsumeRemainingBytesAsString() {
1885ffd83dbSDimitry Andric   return ConsumeBytesAsString(remaining_bytes_);
1895ffd83dbSDimitry Andric }
1905ffd83dbSDimitry Andric 
1915ffd83dbSDimitry Andric // Returns a number in the range [Type's min, Type's max]. The value might
1925ffd83dbSDimitry Andric // not be uniformly distributed in the given range. If there's no input data
1935ffd83dbSDimitry Andric // left, always returns |min|.
ConsumeIntegral()1945ffd83dbSDimitry Andric template <typename T> T FuzzedDataProvider::ConsumeIntegral() {
1955ffd83dbSDimitry Andric   return ConsumeIntegralInRange(std::numeric_limits<T>::min(),
1965ffd83dbSDimitry Andric                                 std::numeric_limits<T>::max());
1975ffd83dbSDimitry Andric }
1985ffd83dbSDimitry Andric 
19968d75effSDimitry Andric // Returns a number in the range [min, max] by consuming bytes from the
20068d75effSDimitry Andric // input data. The value might not be uniformly distributed in the given
20168d75effSDimitry Andric // range. If there's no input data left, always returns |min|. |min| must
20268d75effSDimitry Andric // be less than or equal to |max|.
2035ffd83dbSDimitry Andric template <typename T>
ConsumeIntegralInRange(T min,T max)2045ffd83dbSDimitry Andric T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) {
20568d75effSDimitry Andric   static_assert(std::is_integral<T>::value, "An integral type is required.");
20668d75effSDimitry Andric   static_assert(sizeof(T) <= sizeof(uint64_t), "Unsupported integral type.");
20768d75effSDimitry Andric 
20868d75effSDimitry Andric   if (min > max)
20968d75effSDimitry Andric     abort();
21068d75effSDimitry Andric 
21168d75effSDimitry Andric   // Use the biggest type possible to hold the range and the result.
21206c3fb27SDimitry Andric   uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(min);
21368d75effSDimitry Andric   uint64_t result = 0;
21468d75effSDimitry Andric   size_t offset = 0;
21568d75effSDimitry Andric 
21668d75effSDimitry Andric   while (offset < sizeof(T) * CHAR_BIT && (range >> offset) > 0 &&
21768d75effSDimitry Andric          remaining_bytes_ != 0) {
21868d75effSDimitry Andric     // Pull bytes off the end of the seed data. Experimentally, this seems to
21968d75effSDimitry Andric     // allow the fuzzer to more easily explore the input space. This makes
22068d75effSDimitry Andric     // sense, since it works by modifying inputs that caused new code to run,
22168d75effSDimitry Andric     // and this data is often used to encode length of data read by
22268d75effSDimitry Andric     // |ConsumeBytes|. Separating out read lengths makes it easier modify the
22368d75effSDimitry Andric     // contents of the data that is actually read.
22468d75effSDimitry Andric     --remaining_bytes_;
22568d75effSDimitry Andric     result = (result << CHAR_BIT) | data_ptr_[remaining_bytes_];
22668d75effSDimitry Andric     offset += CHAR_BIT;
22768d75effSDimitry Andric   }
22868d75effSDimitry Andric 
22968d75effSDimitry Andric   // Avoid division by 0, in case |range + 1| results in overflow.
23068d75effSDimitry Andric   if (range != std::numeric_limits<decltype(range)>::max())
23168d75effSDimitry Andric     result = result % (range + 1);
23268d75effSDimitry Andric 
23306c3fb27SDimitry Andric   return static_cast<T>(static_cast<uint64_t>(min) + result);
23468d75effSDimitry Andric }
23568d75effSDimitry Andric 
23668d75effSDimitry Andric // Returns a floating point value in the range [Type's lowest, Type's max] by
23768d75effSDimitry Andric // consuming bytes from the input data. If there's no input data left, always
23868d75effSDimitry Andric // returns approximately 0.
ConsumeFloatingPoint()2395ffd83dbSDimitry Andric template <typename T> T FuzzedDataProvider::ConsumeFloatingPoint() {
24068d75effSDimitry Andric   return ConsumeFloatingPointInRange<T>(std::numeric_limits<T>::lowest(),
24168d75effSDimitry Andric                                         std::numeric_limits<T>::max());
24268d75effSDimitry Andric }
24368d75effSDimitry Andric 
24468d75effSDimitry Andric // Returns a floating point value in the given range by consuming bytes from
24568d75effSDimitry Andric // the input data. If there's no input data left, returns |min|. Note that
24668d75effSDimitry Andric // |min| must be less than or equal to |max|.
2475ffd83dbSDimitry Andric template <typename T>
ConsumeFloatingPointInRange(T min,T max)2485ffd83dbSDimitry Andric T FuzzedDataProvider::ConsumeFloatingPointInRange(T min, T max) {
24968d75effSDimitry Andric   if (min > max)
25068d75effSDimitry Andric     abort();
25168d75effSDimitry Andric 
25268d75effSDimitry Andric   T range = .0;
25368d75effSDimitry Andric   T result = min;
25468d75effSDimitry Andric   constexpr T zero(.0);
25568d75effSDimitry Andric   if (max > zero && min < zero && max > min + std::numeric_limits<T>::max()) {
25668d75effSDimitry Andric     // The diff |max - min| would overflow the given floating point type. Use
25768d75effSDimitry Andric     // the half of the diff as the range and consume a bool to decide whether
25868d75effSDimitry Andric     // the result is in the first of the second part of the diff.
25968d75effSDimitry Andric     range = (max / 2.0) - (min / 2.0);
26068d75effSDimitry Andric     if (ConsumeBool()) {
26168d75effSDimitry Andric       result += range;
26268d75effSDimitry Andric     }
26368d75effSDimitry Andric   } else {
26468d75effSDimitry Andric     range = max - min;
26568d75effSDimitry Andric   }
26668d75effSDimitry Andric 
26768d75effSDimitry Andric   return result + range * ConsumeProbability<T>();
26868d75effSDimitry Andric }
26968d75effSDimitry Andric 
2705ffd83dbSDimitry Andric // Returns a floating point number in the range [0.0, 1.0]. If there's no
2715ffd83dbSDimitry Andric // input data left, always returns 0.
ConsumeProbability()2725ffd83dbSDimitry Andric template <typename T> T FuzzedDataProvider::ConsumeProbability() {
2735ffd83dbSDimitry Andric   static_assert(std::is_floating_point<T>::value,
2745ffd83dbSDimitry Andric                 "A floating point type is required.");
27568d75effSDimitry Andric 
2765ffd83dbSDimitry Andric   // Use different integral types for different floating point types in order
2775ffd83dbSDimitry Andric   // to provide better density of the resulting values.
2785ffd83dbSDimitry Andric   using IntegralType =
2795ffd83dbSDimitry Andric       typename std::conditional<(sizeof(T) <= sizeof(uint32_t)), uint32_t,
2805ffd83dbSDimitry Andric                                 uint64_t>::type;
28168d75effSDimitry Andric 
2825ffd83dbSDimitry Andric   T result = static_cast<T>(ConsumeIntegral<IntegralType>());
2835ffd83dbSDimitry Andric   result /= static_cast<T>(std::numeric_limits<IntegralType>::max());
2845ffd83dbSDimitry Andric   return result;
2855ffd83dbSDimitry Andric }
2865ffd83dbSDimitry Andric 
2875ffd83dbSDimitry Andric // Reads one byte and returns a bool, or false when no data remains.
ConsumeBool()2885ffd83dbSDimitry Andric inline bool FuzzedDataProvider::ConsumeBool() {
2895ffd83dbSDimitry Andric   return 1 & ConsumeIntegral<uint8_t>();
2905ffd83dbSDimitry Andric }
2915ffd83dbSDimitry Andric 
2925ffd83dbSDimitry Andric // Returns an enum value. The enum must start at 0 and be contiguous. It must
2935ffd83dbSDimitry Andric // also contain |kMaxValue| aliased to its largest (inclusive) value. Such as:
2945ffd83dbSDimitry Andric // enum class Foo { SomeValue, OtherValue, kMaxValue = OtherValue };
ConsumeEnum()2955ffd83dbSDimitry Andric template <typename T> T FuzzedDataProvider::ConsumeEnum() {
2965ffd83dbSDimitry Andric   static_assert(std::is_enum<T>::value, "|T| must be an enum type.");
2975ffd83dbSDimitry Andric   return static_cast<T>(
2985ffd83dbSDimitry Andric       ConsumeIntegralInRange<uint32_t>(0, static_cast<uint32_t>(T::kMaxValue)));
2995ffd83dbSDimitry Andric }
3005ffd83dbSDimitry Andric 
3015ffd83dbSDimitry Andric // Returns a copy of the value selected from the given fixed-size |array|.
3025ffd83dbSDimitry Andric template <typename T, size_t size>
PickValueInArray(const T (& array)[size])3035ffd83dbSDimitry Andric T FuzzedDataProvider::PickValueInArray(const T (&array)[size]) {
3045ffd83dbSDimitry Andric   static_assert(size > 0, "The array must be non empty.");
3055ffd83dbSDimitry Andric   return array[ConsumeIntegralInRange<size_t>(0, size - 1)];
3065ffd83dbSDimitry Andric }
3075ffd83dbSDimitry Andric 
308e8d8bef9SDimitry Andric template <typename T, size_t size>
PickValueInArray(const std::array<T,size> & array)309e8d8bef9SDimitry Andric T FuzzedDataProvider::PickValueInArray(const std::array<T, size> &array) {
310e8d8bef9SDimitry Andric   static_assert(size > 0, "The array must be non empty.");
311e8d8bef9SDimitry Andric   return array[ConsumeIntegralInRange<size_t>(0, size - 1)];
312e8d8bef9SDimitry Andric }
313e8d8bef9SDimitry Andric 
3145ffd83dbSDimitry Andric template <typename T>
PickValueInArray(std::initializer_list<const T> list)3155ffd83dbSDimitry Andric T FuzzedDataProvider::PickValueInArray(std::initializer_list<const T> list) {
3165ffd83dbSDimitry Andric   // TODO(Dor1s): switch to static_assert once C++14 is allowed.
3175ffd83dbSDimitry Andric   if (!list.size())
3185ffd83dbSDimitry Andric     abort();
3195ffd83dbSDimitry Andric 
3205ffd83dbSDimitry Andric   return *(list.begin() + ConsumeIntegralInRange<size_t>(0, list.size() - 1));
3215ffd83dbSDimitry Andric }
3225ffd83dbSDimitry Andric 
3235ffd83dbSDimitry Andric // Writes |num_bytes| of input data to the given destination pointer. If there
3245ffd83dbSDimitry Andric // is not enough data left, writes all remaining bytes. Return value is the
3255ffd83dbSDimitry Andric // number of bytes written.
3265ffd83dbSDimitry Andric // In general, it's better to avoid using this function, but it may be useful
3275ffd83dbSDimitry Andric // in cases when it's necessary to fill a certain buffer or object with
3285ffd83dbSDimitry Andric // fuzzing data.
ConsumeData(void * destination,size_t num_bytes)3295ffd83dbSDimitry Andric inline size_t FuzzedDataProvider::ConsumeData(void *destination,
3305ffd83dbSDimitry Andric                                               size_t num_bytes) {
3315ffd83dbSDimitry Andric   num_bytes = std::min(num_bytes, remaining_bytes_);
3325ffd83dbSDimitry Andric   CopyAndAdvance(destination, num_bytes);
3335ffd83dbSDimitry Andric   return num_bytes;
3345ffd83dbSDimitry Andric }
3355ffd83dbSDimitry Andric 
3365ffd83dbSDimitry Andric // Private methods.
CopyAndAdvance(void * destination,size_t num_bytes)3375ffd83dbSDimitry Andric inline void FuzzedDataProvider::CopyAndAdvance(void *destination,
3385ffd83dbSDimitry Andric                                                size_t num_bytes) {
3395ffd83dbSDimitry Andric   std::memcpy(destination, data_ptr_, num_bytes);
3405ffd83dbSDimitry Andric   Advance(num_bytes);
3415ffd83dbSDimitry Andric }
3425ffd83dbSDimitry Andric 
Advance(size_t num_bytes)3435ffd83dbSDimitry Andric inline void FuzzedDataProvider::Advance(size_t num_bytes) {
34468d75effSDimitry Andric   if (num_bytes > remaining_bytes_)
34568d75effSDimitry Andric     abort();
34668d75effSDimitry Andric 
34768d75effSDimitry Andric   data_ptr_ += num_bytes;
34868d75effSDimitry Andric   remaining_bytes_ -= num_bytes;
34968d75effSDimitry Andric }
35068d75effSDimitry Andric 
35168d75effSDimitry Andric template <typename T>
ConsumeBytes(size_t size,size_t num_bytes)3525ffd83dbSDimitry Andric std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t size, size_t num_bytes) {
35368d75effSDimitry Andric   static_assert(sizeof(T) == sizeof(uint8_t), "Incompatible data type.");
35468d75effSDimitry Andric 
35568d75effSDimitry Andric   // The point of using the size-based constructor below is to increase the
35668d75effSDimitry Andric   // odds of having a vector object with capacity being equal to the length.
35768d75effSDimitry Andric   // That part is always implementation specific, but at least both libc++ and
35868d75effSDimitry Andric   // libstdc++ allocate the requested number of bytes in that constructor,
35968d75effSDimitry Andric   // which seems to be a natural choice for other implementations as well.
36068d75effSDimitry Andric   // To increase the odds even more, we also call |shrink_to_fit| below.
36168d75effSDimitry Andric   std::vector<T> result(size);
362480093f4SDimitry Andric   if (size == 0) {
3635ffd83dbSDimitry Andric     if (num_bytes != 0)
364480093f4SDimitry Andric       abort();
365480093f4SDimitry Andric     return result;
366480093f4SDimitry Andric   }
367480093f4SDimitry Andric 
3685ffd83dbSDimitry Andric   CopyAndAdvance(result.data(), num_bytes);
36968d75effSDimitry Andric 
37068d75effSDimitry Andric   // Even though |shrink_to_fit| is also implementation specific, we expect it
37168d75effSDimitry Andric   // to provide an additional assurance in case vector's constructor allocated
37268d75effSDimitry Andric   // a buffer which is larger than the actual amount of data we put inside it.
37368d75effSDimitry Andric   result.shrink_to_fit();
37468d75effSDimitry Andric   return result;
37568d75effSDimitry Andric }
37668d75effSDimitry Andric 
3775ffd83dbSDimitry Andric template <typename TS, typename TU>
ConvertUnsignedToSigned(TU value)3785ffd83dbSDimitry Andric TS FuzzedDataProvider::ConvertUnsignedToSigned(TU value) {
37968d75effSDimitry Andric   static_assert(sizeof(TS) == sizeof(TU), "Incompatible data types.");
38068d75effSDimitry Andric   static_assert(!std::numeric_limits<TU>::is_signed,
38168d75effSDimitry Andric                 "Source type must be unsigned.");
38268d75effSDimitry Andric 
38368d75effSDimitry Andric   // TODO(Dor1s): change to `if constexpr` once C++17 becomes mainstream.
38468d75effSDimitry Andric   if (std::numeric_limits<TS>::is_modulo)
38568d75effSDimitry Andric     return static_cast<TS>(value);
38668d75effSDimitry Andric 
3875ffd83dbSDimitry Andric   // Avoid using implementation-defined unsigned to signed conversions.
38868d75effSDimitry Andric   // To learn more, see https://stackoverflow.com/questions/13150449.
38968d75effSDimitry Andric   if (value <= std::numeric_limits<TS>::max()) {
39068d75effSDimitry Andric     return static_cast<TS>(value);
39168d75effSDimitry Andric   } else {
39268d75effSDimitry Andric     constexpr auto TS_min = std::numeric_limits<TS>::min();
393fe6060f1SDimitry Andric     return TS_min + static_cast<TS>(value - TS_min);
39468d75effSDimitry Andric   }
39568d75effSDimitry Andric }
39668d75effSDimitry Andric 
39768d75effSDimitry Andric #endif // LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
398