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