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