xref: /aosp_15_r20/prebuilts/clang-tools/linux-x86/clang-headers/fuzzer/FuzzedDataProvider.h (revision bed243d3d9cd544cfb038bfa7be843dedc6e6bf7)
1*bed243d3SAndroid Build Coastguard Worker //===- FuzzedDataProvider.h - Utility header for fuzz targets ---*- C++ -* ===//
2*bed243d3SAndroid Build Coastguard Worker //
3*bed243d3SAndroid Build Coastguard Worker // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*bed243d3SAndroid Build Coastguard Worker // See https://llvm.org/LICENSE.txt for license information.
5*bed243d3SAndroid Build Coastguard Worker // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*bed243d3SAndroid Build Coastguard Worker //
7*bed243d3SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
8*bed243d3SAndroid Build Coastguard Worker // A single header library providing an utility class to break up an array of
9*bed243d3SAndroid Build Coastguard Worker // bytes. Whenever run on the same input, provides the same output, as long as
10*bed243d3SAndroid Build Coastguard Worker // its methods are called in the same order, with the same arguments.
11*bed243d3SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
12*bed243d3SAndroid Build Coastguard Worker 
13*bed243d3SAndroid Build Coastguard Worker #ifndef LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
14*bed243d3SAndroid Build Coastguard Worker #define LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
15*bed243d3SAndroid Build Coastguard Worker 
16*bed243d3SAndroid Build Coastguard Worker #include <algorithm>
17*bed243d3SAndroid Build Coastguard Worker #include <array>
18*bed243d3SAndroid Build Coastguard Worker #include <climits>
19*bed243d3SAndroid Build Coastguard Worker #include <cstddef>
20*bed243d3SAndroid Build Coastguard Worker #include <cstdint>
21*bed243d3SAndroid Build Coastguard Worker #include <cstring>
22*bed243d3SAndroid Build Coastguard Worker #include <initializer_list>
23*bed243d3SAndroid Build Coastguard Worker #include <limits>
24*bed243d3SAndroid Build Coastguard Worker #include <string>
25*bed243d3SAndroid Build Coastguard Worker #include <type_traits>
26*bed243d3SAndroid Build Coastguard Worker #include <utility>
27*bed243d3SAndroid Build Coastguard Worker #include <vector>
28*bed243d3SAndroid Build Coastguard Worker 
29*bed243d3SAndroid Build Coastguard Worker // In addition to the comments below, the API is also briefly documented at
30*bed243d3SAndroid Build Coastguard Worker // https://github.com/google/fuzzing/blob/master/docs/split-inputs.md#fuzzed-data-provider
31*bed243d3SAndroid Build Coastguard Worker class FuzzedDataProvider {
32*bed243d3SAndroid Build Coastguard Worker  public:
33*bed243d3SAndroid Build Coastguard Worker   // |data| is an array of length |size| that the FuzzedDataProvider wraps to
34*bed243d3SAndroid Build Coastguard Worker   // provide more granular access. |data| must outlive the FuzzedDataProvider.
FuzzedDataProvider(const uint8_t * data,size_t size)35*bed243d3SAndroid Build Coastguard Worker   FuzzedDataProvider(const uint8_t *data, size_t size)
36*bed243d3SAndroid Build Coastguard Worker       : data_ptr_(data), remaining_bytes_(size) {}
37*bed243d3SAndroid Build Coastguard Worker   ~FuzzedDataProvider() = default;
38*bed243d3SAndroid Build Coastguard Worker 
39*bed243d3SAndroid Build Coastguard Worker   // See the implementation below (after the class definition) for more verbose
40*bed243d3SAndroid Build Coastguard Worker   // comments for each of the methods.
41*bed243d3SAndroid Build Coastguard Worker 
42*bed243d3SAndroid Build Coastguard Worker   // Methods returning std::vector of bytes. These are the most popular choice
43*bed243d3SAndroid Build Coastguard Worker   // when splitting fuzzing input into pieces, as every piece is put into a
44*bed243d3SAndroid Build Coastguard Worker   // separate buffer (i.e. ASan would catch any under-/overflow) and the memory
45*bed243d3SAndroid Build Coastguard Worker   // will be released automatically.
46*bed243d3SAndroid Build Coastguard Worker   template <typename T> std::vector<T> ConsumeBytes(size_t num_bytes);
47*bed243d3SAndroid Build Coastguard Worker   template <typename T>
48*bed243d3SAndroid Build Coastguard Worker   std::vector<T> ConsumeBytesWithTerminator(size_t num_bytes, T terminator = 0);
49*bed243d3SAndroid Build Coastguard Worker   template <typename T> std::vector<T> ConsumeRemainingBytes();
50*bed243d3SAndroid Build Coastguard Worker 
51*bed243d3SAndroid Build Coastguard Worker   // Methods returning strings. Use only when you need a std::string or a null
52*bed243d3SAndroid Build Coastguard Worker   // terminated C-string. Otherwise, prefer the methods returning std::vector.
53*bed243d3SAndroid Build Coastguard Worker   std::string ConsumeBytesAsString(size_t num_bytes);
54*bed243d3SAndroid Build Coastguard Worker   std::string ConsumeRandomLengthString(size_t max_length);
55*bed243d3SAndroid Build Coastguard Worker   std::string ConsumeRandomLengthString();
56*bed243d3SAndroid Build Coastguard Worker   std::string ConsumeRemainingBytesAsString();
57*bed243d3SAndroid Build Coastguard Worker 
58*bed243d3SAndroid Build Coastguard Worker   // Methods returning integer values.
59*bed243d3SAndroid Build Coastguard Worker   template <typename T> T ConsumeIntegral();
60*bed243d3SAndroid Build Coastguard Worker   template <typename T> T ConsumeIntegralInRange(T min, T max);
61*bed243d3SAndroid Build Coastguard Worker 
62*bed243d3SAndroid Build Coastguard Worker   // Methods returning floating point values.
63*bed243d3SAndroid Build Coastguard Worker   template <typename T> T ConsumeFloatingPoint();
64*bed243d3SAndroid Build Coastguard Worker   template <typename T> T ConsumeFloatingPointInRange(T min, T max);
65*bed243d3SAndroid Build Coastguard Worker 
66*bed243d3SAndroid Build Coastguard Worker   // 0 <= return value <= 1.
67*bed243d3SAndroid Build Coastguard Worker   template <typename T> T ConsumeProbability();
68*bed243d3SAndroid Build Coastguard Worker 
69*bed243d3SAndroid Build Coastguard Worker   bool ConsumeBool();
70*bed243d3SAndroid Build Coastguard Worker 
71*bed243d3SAndroid Build Coastguard Worker   // Returns a value chosen from the given enum.
72*bed243d3SAndroid Build Coastguard Worker   template <typename T> T ConsumeEnum();
73*bed243d3SAndroid Build Coastguard Worker 
74*bed243d3SAndroid Build Coastguard Worker   // Returns a value from the given array.
75*bed243d3SAndroid Build Coastguard Worker   template <typename T, size_t size> T PickValueInArray(const T (&array)[size]);
76*bed243d3SAndroid Build Coastguard Worker   template <typename T, size_t size>
77*bed243d3SAndroid Build Coastguard Worker   T PickValueInArray(const std::array<T, size> &array);
78*bed243d3SAndroid Build Coastguard Worker   template <typename T> T PickValueInArray(std::initializer_list<const T> list);
79*bed243d3SAndroid Build Coastguard Worker 
80*bed243d3SAndroid Build Coastguard Worker   // Writes data to the given destination and returns number of bytes written.
81*bed243d3SAndroid Build Coastguard Worker   size_t ConsumeData(void *destination, size_t num_bytes);
82*bed243d3SAndroid Build Coastguard Worker 
83*bed243d3SAndroid Build Coastguard Worker   // Reports the remaining bytes available for fuzzed input.
remaining_bytes()84*bed243d3SAndroid Build Coastguard Worker   size_t remaining_bytes() { return remaining_bytes_; }
85*bed243d3SAndroid Build Coastguard Worker 
86*bed243d3SAndroid Build Coastguard Worker  private:
87*bed243d3SAndroid Build Coastguard Worker   FuzzedDataProvider(const FuzzedDataProvider &) = delete;
88*bed243d3SAndroid Build Coastguard Worker   FuzzedDataProvider &operator=(const FuzzedDataProvider &) = delete;
89*bed243d3SAndroid Build Coastguard Worker 
90*bed243d3SAndroid Build Coastguard Worker   void CopyAndAdvance(void *destination, size_t num_bytes);
91*bed243d3SAndroid Build Coastguard Worker 
92*bed243d3SAndroid Build Coastguard Worker   void Advance(size_t num_bytes);
93*bed243d3SAndroid Build Coastguard Worker 
94*bed243d3SAndroid Build Coastguard Worker   template <typename T>
95*bed243d3SAndroid Build Coastguard Worker   std::vector<T> ConsumeBytes(size_t size, size_t num_bytes);
96*bed243d3SAndroid Build Coastguard Worker 
97*bed243d3SAndroid Build Coastguard Worker   template <typename TS, typename TU> TS ConvertUnsignedToSigned(TU value);
98*bed243d3SAndroid Build Coastguard Worker 
99*bed243d3SAndroid Build Coastguard Worker   const uint8_t *data_ptr_;
100*bed243d3SAndroid Build Coastguard Worker   size_t remaining_bytes_;
101*bed243d3SAndroid Build Coastguard Worker };
102*bed243d3SAndroid Build Coastguard Worker 
103*bed243d3SAndroid Build Coastguard Worker // Returns a std::vector containing |num_bytes| of input data. If fewer than
104*bed243d3SAndroid Build Coastguard Worker // |num_bytes| of data remain, returns a shorter std::vector containing all
105*bed243d3SAndroid Build Coastguard Worker // of the data that's left. Can be used with any byte sized type, such as
106*bed243d3SAndroid Build Coastguard Worker // char, unsigned char, uint8_t, etc.
107*bed243d3SAndroid Build Coastguard Worker template <typename T>
ConsumeBytes(size_t num_bytes)108*bed243d3SAndroid Build Coastguard Worker std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t num_bytes) {
109*bed243d3SAndroid Build Coastguard Worker   num_bytes = std::min(num_bytes, remaining_bytes_);
110*bed243d3SAndroid Build Coastguard Worker   return ConsumeBytes<T>(num_bytes, num_bytes);
111*bed243d3SAndroid Build Coastguard Worker }
112*bed243d3SAndroid Build Coastguard Worker 
113*bed243d3SAndroid Build Coastguard Worker // Similar to |ConsumeBytes|, but also appends the terminator value at the end
114*bed243d3SAndroid Build Coastguard Worker // of the resulting vector. Useful, when a mutable null-terminated C-string is
115*bed243d3SAndroid Build Coastguard Worker // needed, for example. But that is a rare case. Better avoid it, if possible,
116*bed243d3SAndroid Build Coastguard Worker // and prefer using |ConsumeBytes| or |ConsumeBytesAsString| methods.
117*bed243d3SAndroid Build Coastguard Worker template <typename T>
ConsumeBytesWithTerminator(size_t num_bytes,T terminator)118*bed243d3SAndroid Build Coastguard Worker std::vector<T> FuzzedDataProvider::ConsumeBytesWithTerminator(size_t num_bytes,
119*bed243d3SAndroid Build Coastguard Worker                                                               T terminator) {
120*bed243d3SAndroid Build Coastguard Worker   num_bytes = std::min(num_bytes, remaining_bytes_);
121*bed243d3SAndroid Build Coastguard Worker   std::vector<T> result = ConsumeBytes<T>(num_bytes + 1, num_bytes);
122*bed243d3SAndroid Build Coastguard Worker   result.back() = terminator;
123*bed243d3SAndroid Build Coastguard Worker   return result;
124*bed243d3SAndroid Build Coastguard Worker }
125*bed243d3SAndroid Build Coastguard Worker 
126*bed243d3SAndroid Build Coastguard Worker // Returns a std::vector containing all remaining bytes of the input data.
127*bed243d3SAndroid Build Coastguard Worker template <typename T>
ConsumeRemainingBytes()128*bed243d3SAndroid Build Coastguard Worker std::vector<T> FuzzedDataProvider::ConsumeRemainingBytes() {
129*bed243d3SAndroid Build Coastguard Worker   return ConsumeBytes<T>(remaining_bytes_);
130*bed243d3SAndroid Build Coastguard Worker }
131*bed243d3SAndroid Build Coastguard Worker 
132*bed243d3SAndroid Build Coastguard Worker // Returns a std::string containing |num_bytes| of input data. Using this and
133*bed243d3SAndroid Build Coastguard Worker // |.c_str()| on the resulting string is the best way to get an immutable
134*bed243d3SAndroid Build Coastguard Worker // null-terminated C string. If fewer than |num_bytes| of data remain, returns
135*bed243d3SAndroid Build Coastguard Worker // a shorter std::string containing all of the data that's left.
ConsumeBytesAsString(size_t num_bytes)136*bed243d3SAndroid Build Coastguard Worker inline std::string FuzzedDataProvider::ConsumeBytesAsString(size_t num_bytes) {
137*bed243d3SAndroid Build Coastguard Worker   static_assert(sizeof(std::string::value_type) == sizeof(uint8_t),
138*bed243d3SAndroid Build Coastguard Worker                 "ConsumeBytesAsString cannot convert the data to a string.");
139*bed243d3SAndroid Build Coastguard Worker 
140*bed243d3SAndroid Build Coastguard Worker   num_bytes = std::min(num_bytes, remaining_bytes_);
141*bed243d3SAndroid Build Coastguard Worker   std::string result(
142*bed243d3SAndroid Build Coastguard Worker       reinterpret_cast<const std::string::value_type *>(data_ptr_), num_bytes);
143*bed243d3SAndroid Build Coastguard Worker   Advance(num_bytes);
144*bed243d3SAndroid Build Coastguard Worker   return result;
145*bed243d3SAndroid Build Coastguard Worker }
146*bed243d3SAndroid Build Coastguard Worker 
147*bed243d3SAndroid Build Coastguard Worker // Returns a std::string of length from 0 to |max_length|. When it runs out of
148*bed243d3SAndroid Build Coastguard Worker // input data, returns what remains of the input. Designed to be more stable
149*bed243d3SAndroid Build Coastguard Worker // with respect to a fuzzer inserting characters than just picking a random
150*bed243d3SAndroid Build Coastguard Worker // length and then consuming that many bytes with |ConsumeBytes|.
151*bed243d3SAndroid Build Coastguard Worker inline std::string
ConsumeRandomLengthString(size_t max_length)152*bed243d3SAndroid Build Coastguard Worker FuzzedDataProvider::ConsumeRandomLengthString(size_t max_length) {
153*bed243d3SAndroid Build Coastguard Worker   // Reads bytes from the start of |data_ptr_|. Maps "\\" to "\", and maps "\"
154*bed243d3SAndroid Build Coastguard Worker   // followed by anything else to the end of the string. As a result of this
155*bed243d3SAndroid Build Coastguard Worker   // logic, a fuzzer can insert characters into the string, and the string
156*bed243d3SAndroid Build Coastguard Worker   // will be lengthened to include those new characters, resulting in a more
157*bed243d3SAndroid Build Coastguard Worker   // stable fuzzer than picking the length of a string independently from
158*bed243d3SAndroid Build Coastguard Worker   // picking its contents.
159*bed243d3SAndroid Build Coastguard Worker   std::string result;
160*bed243d3SAndroid Build Coastguard Worker 
161*bed243d3SAndroid Build Coastguard Worker   // Reserve the anticipated capacity to prevent several reallocations.
162*bed243d3SAndroid Build Coastguard Worker   result.reserve(std::min(max_length, remaining_bytes_));
163*bed243d3SAndroid Build Coastguard Worker   for (size_t i = 0; i < max_length && remaining_bytes_ != 0; ++i) {
164*bed243d3SAndroid Build Coastguard Worker     char next = ConvertUnsignedToSigned<char>(data_ptr_[0]);
165*bed243d3SAndroid Build Coastguard Worker     Advance(1);
166*bed243d3SAndroid Build Coastguard Worker     if (next == '\\' && remaining_bytes_ != 0) {
167*bed243d3SAndroid Build Coastguard Worker       next = ConvertUnsignedToSigned<char>(data_ptr_[0]);
168*bed243d3SAndroid Build Coastguard Worker       Advance(1);
169*bed243d3SAndroid Build Coastguard Worker       if (next != '\\')
170*bed243d3SAndroid Build Coastguard Worker         break;
171*bed243d3SAndroid Build Coastguard Worker     }
172*bed243d3SAndroid Build Coastguard Worker     result += next;
173*bed243d3SAndroid Build Coastguard Worker   }
174*bed243d3SAndroid Build Coastguard Worker 
175*bed243d3SAndroid Build Coastguard Worker   result.shrink_to_fit();
176*bed243d3SAndroid Build Coastguard Worker   return result;
177*bed243d3SAndroid Build Coastguard Worker }
178*bed243d3SAndroid Build Coastguard Worker 
179*bed243d3SAndroid Build Coastguard Worker // Returns a std::string of length from 0 to |remaining_bytes_|.
ConsumeRandomLengthString()180*bed243d3SAndroid Build Coastguard Worker inline std::string FuzzedDataProvider::ConsumeRandomLengthString() {
181*bed243d3SAndroid Build Coastguard Worker   return ConsumeRandomLengthString(remaining_bytes_);
182*bed243d3SAndroid Build Coastguard Worker }
183*bed243d3SAndroid Build Coastguard Worker 
184*bed243d3SAndroid Build Coastguard Worker // Returns a std::string containing all remaining bytes of the input data.
185*bed243d3SAndroid Build Coastguard Worker // Prefer using |ConsumeRemainingBytes| unless you actually need a std::string
186*bed243d3SAndroid Build Coastguard Worker // object.
ConsumeRemainingBytesAsString()187*bed243d3SAndroid Build Coastguard Worker inline std::string FuzzedDataProvider::ConsumeRemainingBytesAsString() {
188*bed243d3SAndroid Build Coastguard Worker   return ConsumeBytesAsString(remaining_bytes_);
189*bed243d3SAndroid Build Coastguard Worker }
190*bed243d3SAndroid Build Coastguard Worker 
191*bed243d3SAndroid Build Coastguard Worker // Returns a number in the range [Type's min, Type's max]. The value might
192*bed243d3SAndroid Build Coastguard Worker // not be uniformly distributed in the given range. If there's no input data
193*bed243d3SAndroid Build Coastguard Worker // left, always returns |min|.
ConsumeIntegral()194*bed243d3SAndroid Build Coastguard Worker template <typename T> T FuzzedDataProvider::ConsumeIntegral() {
195*bed243d3SAndroid Build Coastguard Worker   return ConsumeIntegralInRange(std::numeric_limits<T>::min(),
196*bed243d3SAndroid Build Coastguard Worker                                 std::numeric_limits<T>::max());
197*bed243d3SAndroid Build Coastguard Worker }
198*bed243d3SAndroid Build Coastguard Worker 
199*bed243d3SAndroid Build Coastguard Worker // Returns a number in the range [min, max] by consuming bytes from the
200*bed243d3SAndroid Build Coastguard Worker // input data. The value might not be uniformly distributed in the given
201*bed243d3SAndroid Build Coastguard Worker // range. If there's no input data left, always returns |min|. |min| must
202*bed243d3SAndroid Build Coastguard Worker // be less than or equal to |max|.
203*bed243d3SAndroid Build Coastguard Worker template <typename T>
ConsumeIntegralInRange(T min,T max)204*bed243d3SAndroid Build Coastguard Worker T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) {
205*bed243d3SAndroid Build Coastguard Worker   static_assert(std::is_integral<T>::value, "An integral type is required.");
206*bed243d3SAndroid Build Coastguard Worker   static_assert(sizeof(T) <= sizeof(uint64_t), "Unsupported integral type.");
207*bed243d3SAndroid Build Coastguard Worker 
208*bed243d3SAndroid Build Coastguard Worker   if (min > max)
209*bed243d3SAndroid Build Coastguard Worker     abort();
210*bed243d3SAndroid Build Coastguard Worker 
211*bed243d3SAndroid Build Coastguard Worker   // Use the biggest type possible to hold the range and the result.
212*bed243d3SAndroid Build Coastguard Worker   uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(min);
213*bed243d3SAndroid Build Coastguard Worker   uint64_t result = 0;
214*bed243d3SAndroid Build Coastguard Worker   size_t offset = 0;
215*bed243d3SAndroid Build Coastguard Worker 
216*bed243d3SAndroid Build Coastguard Worker   while (offset < sizeof(T) * CHAR_BIT && (range >> offset) > 0 &&
217*bed243d3SAndroid Build Coastguard Worker          remaining_bytes_ != 0) {
218*bed243d3SAndroid Build Coastguard Worker     // Pull bytes off the end of the seed data. Experimentally, this seems to
219*bed243d3SAndroid Build Coastguard Worker     // allow the fuzzer to more easily explore the input space. This makes
220*bed243d3SAndroid Build Coastguard Worker     // sense, since it works by modifying inputs that caused new code to run,
221*bed243d3SAndroid Build Coastguard Worker     // and this data is often used to encode length of data read by
222*bed243d3SAndroid Build Coastguard Worker     // |ConsumeBytes|. Separating out read lengths makes it easier modify the
223*bed243d3SAndroid Build Coastguard Worker     // contents of the data that is actually read.
224*bed243d3SAndroid Build Coastguard Worker     --remaining_bytes_;
225*bed243d3SAndroid Build Coastguard Worker     result = (result << CHAR_BIT) | data_ptr_[remaining_bytes_];
226*bed243d3SAndroid Build Coastguard Worker     offset += CHAR_BIT;
227*bed243d3SAndroid Build Coastguard Worker   }
228*bed243d3SAndroid Build Coastguard Worker 
229*bed243d3SAndroid Build Coastguard Worker   // Avoid division by 0, in case |range + 1| results in overflow.
230*bed243d3SAndroid Build Coastguard Worker   if (range != std::numeric_limits<decltype(range)>::max())
231*bed243d3SAndroid Build Coastguard Worker     result = result % (range + 1);
232*bed243d3SAndroid Build Coastguard Worker 
233*bed243d3SAndroid Build Coastguard Worker   return static_cast<T>(static_cast<uint64_t>(min) + result);
234*bed243d3SAndroid Build Coastguard Worker }
235*bed243d3SAndroid Build Coastguard Worker 
236*bed243d3SAndroid Build Coastguard Worker // Returns a floating point value in the range [Type's lowest, Type's max] by
237*bed243d3SAndroid Build Coastguard Worker // consuming bytes from the input data. If there's no input data left, always
238*bed243d3SAndroid Build Coastguard Worker // returns approximately 0.
ConsumeFloatingPoint()239*bed243d3SAndroid Build Coastguard Worker template <typename T> T FuzzedDataProvider::ConsumeFloatingPoint() {
240*bed243d3SAndroid Build Coastguard Worker   return ConsumeFloatingPointInRange<T>(std::numeric_limits<T>::lowest(),
241*bed243d3SAndroid Build Coastguard Worker                                         std::numeric_limits<T>::max());
242*bed243d3SAndroid Build Coastguard Worker }
243*bed243d3SAndroid Build Coastguard Worker 
244*bed243d3SAndroid Build Coastguard Worker // Returns a floating point value in the given range by consuming bytes from
245*bed243d3SAndroid Build Coastguard Worker // the input data. If there's no input data left, returns |min|. Note that
246*bed243d3SAndroid Build Coastguard Worker // |min| must be less than or equal to |max|.
247*bed243d3SAndroid Build Coastguard Worker template <typename T>
ConsumeFloatingPointInRange(T min,T max)248*bed243d3SAndroid Build Coastguard Worker T FuzzedDataProvider::ConsumeFloatingPointInRange(T min, T max) {
249*bed243d3SAndroid Build Coastguard Worker   if (min > max)
250*bed243d3SAndroid Build Coastguard Worker     abort();
251*bed243d3SAndroid Build Coastguard Worker 
252*bed243d3SAndroid Build Coastguard Worker   T range = .0;
253*bed243d3SAndroid Build Coastguard Worker   T result = min;
254*bed243d3SAndroid Build Coastguard Worker   constexpr T zero(.0);
255*bed243d3SAndroid Build Coastguard Worker   if (max > zero && min < zero && max > min + std::numeric_limits<T>::max()) {
256*bed243d3SAndroid Build Coastguard Worker     // The diff |max - min| would overflow the given floating point type. Use
257*bed243d3SAndroid Build Coastguard Worker     // the half of the diff as the range and consume a bool to decide whether
258*bed243d3SAndroid Build Coastguard Worker     // the result is in the first of the second part of the diff.
259*bed243d3SAndroid Build Coastguard Worker     range = (max / 2.0) - (min / 2.0);
260*bed243d3SAndroid Build Coastguard Worker     if (ConsumeBool()) {
261*bed243d3SAndroid Build Coastguard Worker       result += range;
262*bed243d3SAndroid Build Coastguard Worker     }
263*bed243d3SAndroid Build Coastguard Worker   } else {
264*bed243d3SAndroid Build Coastguard Worker     range = max - min;
265*bed243d3SAndroid Build Coastguard Worker   }
266*bed243d3SAndroid Build Coastguard Worker 
267*bed243d3SAndroid Build Coastguard Worker   return result + range * ConsumeProbability<T>();
268*bed243d3SAndroid Build Coastguard Worker }
269*bed243d3SAndroid Build Coastguard Worker 
270*bed243d3SAndroid Build Coastguard Worker // Returns a floating point number in the range [0.0, 1.0]. If there's no
271*bed243d3SAndroid Build Coastguard Worker // input data left, always returns 0.
ConsumeProbability()272*bed243d3SAndroid Build Coastguard Worker template <typename T> T FuzzedDataProvider::ConsumeProbability() {
273*bed243d3SAndroid Build Coastguard Worker   static_assert(std::is_floating_point<T>::value,
274*bed243d3SAndroid Build Coastguard Worker                 "A floating point type is required.");
275*bed243d3SAndroid Build Coastguard Worker 
276*bed243d3SAndroid Build Coastguard Worker   // Use different integral types for different floating point types in order
277*bed243d3SAndroid Build Coastguard Worker   // to provide better density of the resulting values.
278*bed243d3SAndroid Build Coastguard Worker   using IntegralType =
279*bed243d3SAndroid Build Coastguard Worker       typename std::conditional<(sizeof(T) <= sizeof(uint32_t)), uint32_t,
280*bed243d3SAndroid Build Coastguard Worker                                 uint64_t>::type;
281*bed243d3SAndroid Build Coastguard Worker 
282*bed243d3SAndroid Build Coastguard Worker   T result = static_cast<T>(ConsumeIntegral<IntegralType>());
283*bed243d3SAndroid Build Coastguard Worker   result /= static_cast<T>(std::numeric_limits<IntegralType>::max());
284*bed243d3SAndroid Build Coastguard Worker   return result;
285*bed243d3SAndroid Build Coastguard Worker }
286*bed243d3SAndroid Build Coastguard Worker 
287*bed243d3SAndroid Build Coastguard Worker // Reads one byte and returns a bool, or false when no data remains.
ConsumeBool()288*bed243d3SAndroid Build Coastguard Worker inline bool FuzzedDataProvider::ConsumeBool() {
289*bed243d3SAndroid Build Coastguard Worker   return 1 & ConsumeIntegral<uint8_t>();
290*bed243d3SAndroid Build Coastguard Worker }
291*bed243d3SAndroid Build Coastguard Worker 
292*bed243d3SAndroid Build Coastguard Worker // Returns an enum value. The enum must start at 0 and be contiguous. It must
293*bed243d3SAndroid Build Coastguard Worker // also contain |kMaxValue| aliased to its largest (inclusive) value. Such as:
294*bed243d3SAndroid Build Coastguard Worker // enum class Foo { SomeValue, OtherValue, kMaxValue = OtherValue };
ConsumeEnum()295*bed243d3SAndroid Build Coastguard Worker template <typename T> T FuzzedDataProvider::ConsumeEnum() {
296*bed243d3SAndroid Build Coastguard Worker   static_assert(std::is_enum<T>::value, "|T| must be an enum type.");
297*bed243d3SAndroid Build Coastguard Worker   return static_cast<T>(
298*bed243d3SAndroid Build Coastguard Worker       ConsumeIntegralInRange<uint32_t>(0, static_cast<uint32_t>(T::kMaxValue)));
299*bed243d3SAndroid Build Coastguard Worker }
300*bed243d3SAndroid Build Coastguard Worker 
301*bed243d3SAndroid Build Coastguard Worker // Returns a copy of the value selected from the given fixed-size |array|.
302*bed243d3SAndroid Build Coastguard Worker template <typename T, size_t size>
PickValueInArray(const T (& array)[size])303*bed243d3SAndroid Build Coastguard Worker T FuzzedDataProvider::PickValueInArray(const T (&array)[size]) {
304*bed243d3SAndroid Build Coastguard Worker   static_assert(size > 0, "The array must be non empty.");
305*bed243d3SAndroid Build Coastguard Worker   return array[ConsumeIntegralInRange<size_t>(0, size - 1)];
306*bed243d3SAndroid Build Coastguard Worker }
307*bed243d3SAndroid Build Coastguard Worker 
308*bed243d3SAndroid Build Coastguard Worker template <typename T, size_t size>
PickValueInArray(const std::array<T,size> & array)309*bed243d3SAndroid Build Coastguard Worker T FuzzedDataProvider::PickValueInArray(const std::array<T, size> &array) {
310*bed243d3SAndroid Build Coastguard Worker   static_assert(size > 0, "The array must be non empty.");
311*bed243d3SAndroid Build Coastguard Worker   return array[ConsumeIntegralInRange<size_t>(0, size - 1)];
312*bed243d3SAndroid Build Coastguard Worker }
313*bed243d3SAndroid Build Coastguard Worker 
314*bed243d3SAndroid Build Coastguard Worker template <typename T>
PickValueInArray(std::initializer_list<const T> list)315*bed243d3SAndroid Build Coastguard Worker T FuzzedDataProvider::PickValueInArray(std::initializer_list<const T> list) {
316*bed243d3SAndroid Build Coastguard Worker   // TODO(Dor1s): switch to static_assert once C++14 is allowed.
317*bed243d3SAndroid Build Coastguard Worker   if (!list.size())
318*bed243d3SAndroid Build Coastguard Worker     abort();
319*bed243d3SAndroid Build Coastguard Worker 
320*bed243d3SAndroid Build Coastguard Worker   return *(list.begin() + ConsumeIntegralInRange<size_t>(0, list.size() - 1));
321*bed243d3SAndroid Build Coastguard Worker }
322*bed243d3SAndroid Build Coastguard Worker 
323*bed243d3SAndroid Build Coastguard Worker // Writes |num_bytes| of input data to the given destination pointer. If there
324*bed243d3SAndroid Build Coastguard Worker // is not enough data left, writes all remaining bytes. Return value is the
325*bed243d3SAndroid Build Coastguard Worker // number of bytes written.
326*bed243d3SAndroid Build Coastguard Worker // In general, it's better to avoid using this function, but it may be useful
327*bed243d3SAndroid Build Coastguard Worker // in cases when it's necessary to fill a certain buffer or object with
328*bed243d3SAndroid Build Coastguard Worker // fuzzing data.
ConsumeData(void * destination,size_t num_bytes)329*bed243d3SAndroid Build Coastguard Worker inline size_t FuzzedDataProvider::ConsumeData(void *destination,
330*bed243d3SAndroid Build Coastguard Worker                                               size_t num_bytes) {
331*bed243d3SAndroid Build Coastguard Worker   num_bytes = std::min(num_bytes, remaining_bytes_);
332*bed243d3SAndroid Build Coastguard Worker   CopyAndAdvance(destination, num_bytes);
333*bed243d3SAndroid Build Coastguard Worker   return num_bytes;
334*bed243d3SAndroid Build Coastguard Worker }
335*bed243d3SAndroid Build Coastguard Worker 
336*bed243d3SAndroid Build Coastguard Worker // Private methods.
CopyAndAdvance(void * destination,size_t num_bytes)337*bed243d3SAndroid Build Coastguard Worker inline void FuzzedDataProvider::CopyAndAdvance(void *destination,
338*bed243d3SAndroid Build Coastguard Worker                                                size_t num_bytes) {
339*bed243d3SAndroid Build Coastguard Worker   std::memcpy(destination, data_ptr_, num_bytes);
340*bed243d3SAndroid Build Coastguard Worker   Advance(num_bytes);
341*bed243d3SAndroid Build Coastguard Worker }
342*bed243d3SAndroid Build Coastguard Worker 
Advance(size_t num_bytes)343*bed243d3SAndroid Build Coastguard Worker inline void FuzzedDataProvider::Advance(size_t num_bytes) {
344*bed243d3SAndroid Build Coastguard Worker   if (num_bytes > remaining_bytes_)
345*bed243d3SAndroid Build Coastguard Worker     abort();
346*bed243d3SAndroid Build Coastguard Worker 
347*bed243d3SAndroid Build Coastguard Worker   data_ptr_ += num_bytes;
348*bed243d3SAndroid Build Coastguard Worker   remaining_bytes_ -= num_bytes;
349*bed243d3SAndroid Build Coastguard Worker }
350*bed243d3SAndroid Build Coastguard Worker 
351*bed243d3SAndroid Build Coastguard Worker template <typename T>
ConsumeBytes(size_t size,size_t num_bytes)352*bed243d3SAndroid Build Coastguard Worker std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t size, size_t num_bytes) {
353*bed243d3SAndroid Build Coastguard Worker   static_assert(sizeof(T) == sizeof(uint8_t), "Incompatible data type.");
354*bed243d3SAndroid Build Coastguard Worker 
355*bed243d3SAndroid Build Coastguard Worker   // The point of using the size-based constructor below is to increase the
356*bed243d3SAndroid Build Coastguard Worker   // odds of having a vector object with capacity being equal to the length.
357*bed243d3SAndroid Build Coastguard Worker   // That part is always implementation specific, but at least both libc++ and
358*bed243d3SAndroid Build Coastguard Worker   // libstdc++ allocate the requested number of bytes in that constructor,
359*bed243d3SAndroid Build Coastguard Worker   // which seems to be a natural choice for other implementations as well.
360*bed243d3SAndroid Build Coastguard Worker   // To increase the odds even more, we also call |shrink_to_fit| below.
361*bed243d3SAndroid Build Coastguard Worker   std::vector<T> result(size);
362*bed243d3SAndroid Build Coastguard Worker   if (size == 0) {
363*bed243d3SAndroid Build Coastguard Worker     if (num_bytes != 0)
364*bed243d3SAndroid Build Coastguard Worker       abort();
365*bed243d3SAndroid Build Coastguard Worker     return result;
366*bed243d3SAndroid Build Coastguard Worker   }
367*bed243d3SAndroid Build Coastguard Worker 
368*bed243d3SAndroid Build Coastguard Worker   CopyAndAdvance(result.data(), num_bytes);
369*bed243d3SAndroid Build Coastguard Worker 
370*bed243d3SAndroid Build Coastguard Worker   // Even though |shrink_to_fit| is also implementation specific, we expect it
371*bed243d3SAndroid Build Coastguard Worker   // to provide an additional assurance in case vector's constructor allocated
372*bed243d3SAndroid Build Coastguard Worker   // a buffer which is larger than the actual amount of data we put inside it.
373*bed243d3SAndroid Build Coastguard Worker   result.shrink_to_fit();
374*bed243d3SAndroid Build Coastguard Worker   return result;
375*bed243d3SAndroid Build Coastguard Worker }
376*bed243d3SAndroid Build Coastguard Worker 
377*bed243d3SAndroid Build Coastguard Worker template <typename TS, typename TU>
ConvertUnsignedToSigned(TU value)378*bed243d3SAndroid Build Coastguard Worker TS FuzzedDataProvider::ConvertUnsignedToSigned(TU value) {
379*bed243d3SAndroid Build Coastguard Worker   static_assert(sizeof(TS) == sizeof(TU), "Incompatible data types.");
380*bed243d3SAndroid Build Coastguard Worker   static_assert(!std::numeric_limits<TU>::is_signed,
381*bed243d3SAndroid Build Coastguard Worker                 "Source type must be unsigned.");
382*bed243d3SAndroid Build Coastguard Worker 
383*bed243d3SAndroid Build Coastguard Worker   // TODO(Dor1s): change to `if constexpr` once C++17 becomes mainstream.
384*bed243d3SAndroid Build Coastguard Worker   if (std::numeric_limits<TS>::is_modulo)
385*bed243d3SAndroid Build Coastguard Worker     return static_cast<TS>(value);
386*bed243d3SAndroid Build Coastguard Worker 
387*bed243d3SAndroid Build Coastguard Worker   // Avoid using implementation-defined unsigned to signed conversions.
388*bed243d3SAndroid Build Coastguard Worker   // To learn more, see https://stackoverflow.com/questions/13150449.
389*bed243d3SAndroid Build Coastguard Worker   if (value <= std::numeric_limits<TS>::max()) {
390*bed243d3SAndroid Build Coastguard Worker     return static_cast<TS>(value);
391*bed243d3SAndroid Build Coastguard Worker   } else {
392*bed243d3SAndroid Build Coastguard Worker     constexpr auto TS_min = std::numeric_limits<TS>::min();
393*bed243d3SAndroid Build Coastguard Worker     return TS_min + static_cast<TS>(value - TS_min);
394*bed243d3SAndroid Build Coastguard Worker   }
395*bed243d3SAndroid Build Coastguard Worker }
396*bed243d3SAndroid Build Coastguard Worker 
397*bed243d3SAndroid Build Coastguard Worker #endif // LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_
398