Path: blob/main/contrib/llvm-project/compiler-rt/include/fuzzer/FuzzedDataProvider.h
35233 views
//===- FuzzedDataProvider.h - Utility header for fuzz targets ---*- C++ -* ===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7// A single header library providing an utility class to break up an array of8// bytes. Whenever run on the same input, provides the same output, as long as9// its methods are called in the same order, with the same arguments.10//===----------------------------------------------------------------------===//1112#ifndef LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_13#define LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_1415#include <algorithm>16#include <array>17#include <climits>18#include <cstddef>19#include <cstdint>20#include <cstring>21#include <initializer_list>22#include <limits>23#include <string>24#include <type_traits>25#include <utility>26#include <vector>2728// In addition to the comments below, the API is also briefly documented at29// https://github.com/google/fuzzing/blob/master/docs/split-inputs.md#fuzzed-data-provider30class FuzzedDataProvider {31public:32// |data| is an array of length |size| that the FuzzedDataProvider wraps to33// provide more granular access. |data| must outlive the FuzzedDataProvider.34FuzzedDataProvider(const uint8_t *data, size_t size)35: data_ptr_(data), remaining_bytes_(size) {}36~FuzzedDataProvider() = default;3738// See the implementation below (after the class definition) for more verbose39// comments for each of the methods.4041// Methods returning std::vector of bytes. These are the most popular choice42// when splitting fuzzing input into pieces, as every piece is put into a43// separate buffer (i.e. ASan would catch any under-/overflow) and the memory44// will be released automatically.45template <typename T> std::vector<T> ConsumeBytes(size_t num_bytes);46template <typename T>47std::vector<T> ConsumeBytesWithTerminator(size_t num_bytes, T terminator = 0);48template <typename T> std::vector<T> ConsumeRemainingBytes();4950// Methods returning strings. Use only when you need a std::string or a null51// terminated C-string. Otherwise, prefer the methods returning std::vector.52std::string ConsumeBytesAsString(size_t num_bytes);53std::string ConsumeRandomLengthString(size_t max_length);54std::string ConsumeRandomLengthString();55std::string ConsumeRemainingBytesAsString();5657// Methods returning integer values.58template <typename T> T ConsumeIntegral();59template <typename T> T ConsumeIntegralInRange(T min, T max);6061// Methods returning floating point values.62template <typename T> T ConsumeFloatingPoint();63template <typename T> T ConsumeFloatingPointInRange(T min, T max);6465// 0 <= return value <= 1.66template <typename T> T ConsumeProbability();6768bool ConsumeBool();6970// Returns a value chosen from the given enum.71template <typename T> T ConsumeEnum();7273// Returns a value from the given array.74template <typename T, size_t size> T PickValueInArray(const T (&array)[size]);75template <typename T, size_t size>76T PickValueInArray(const std::array<T, size> &array);77template <typename T> T PickValueInArray(std::initializer_list<const T> list);7879// Writes data to the given destination and returns number of bytes written.80size_t ConsumeData(void *destination, size_t num_bytes);8182// Reports the remaining bytes available for fuzzed input.83size_t remaining_bytes() { return remaining_bytes_; }8485private:86FuzzedDataProvider(const FuzzedDataProvider &) = delete;87FuzzedDataProvider &operator=(const FuzzedDataProvider &) = delete;8889void CopyAndAdvance(void *destination, size_t num_bytes);9091void Advance(size_t num_bytes);9293template <typename T>94std::vector<T> ConsumeBytes(size_t size, size_t num_bytes);9596template <typename TS, typename TU> TS ConvertUnsignedToSigned(TU value);9798const uint8_t *data_ptr_;99size_t remaining_bytes_;100};101102// Returns a std::vector containing |num_bytes| of input data. If fewer than103// |num_bytes| of data remain, returns a shorter std::vector containing all104// of the data that's left. Can be used with any byte sized type, such as105// char, unsigned char, uint8_t, etc.106template <typename T>107std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t num_bytes) {108num_bytes = std::min(num_bytes, remaining_bytes_);109return ConsumeBytes<T>(num_bytes, num_bytes);110}111112// Similar to |ConsumeBytes|, but also appends the terminator value at the end113// of the resulting vector. Useful, when a mutable null-terminated C-string is114// needed, for example. But that is a rare case. Better avoid it, if possible,115// and prefer using |ConsumeBytes| or |ConsumeBytesAsString| methods.116template <typename T>117std::vector<T> FuzzedDataProvider::ConsumeBytesWithTerminator(size_t num_bytes,118T terminator) {119num_bytes = std::min(num_bytes, remaining_bytes_);120std::vector<T> result = ConsumeBytes<T>(num_bytes + 1, num_bytes);121result.back() = terminator;122return result;123}124125// Returns a std::vector containing all remaining bytes of the input data.126template <typename T>127std::vector<T> FuzzedDataProvider::ConsumeRemainingBytes() {128return ConsumeBytes<T>(remaining_bytes_);129}130131// Returns a std::string containing |num_bytes| of input data. Using this and132// |.c_str()| on the resulting string is the best way to get an immutable133// null-terminated C string. If fewer than |num_bytes| of data remain, returns134// a shorter std::string containing all of the data that's left.135inline std::string FuzzedDataProvider::ConsumeBytesAsString(size_t num_bytes) {136static_assert(sizeof(std::string::value_type) == sizeof(uint8_t),137"ConsumeBytesAsString cannot convert the data to a string.");138139num_bytes = std::min(num_bytes, remaining_bytes_);140std::string result(141reinterpret_cast<const std::string::value_type *>(data_ptr_), num_bytes);142Advance(num_bytes);143return result;144}145146// Returns a std::string of length from 0 to |max_length|. When it runs out of147// input data, returns what remains of the input. Designed to be more stable148// with respect to a fuzzer inserting characters than just picking a random149// length and then consuming that many bytes with |ConsumeBytes|.150inline std::string151FuzzedDataProvider::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 this154// logic, a fuzzer can insert characters into the string, and the string155// will be lengthened to include those new characters, resulting in a more156// stable fuzzer than picking the length of a string independently from157// picking its contents.158std::string result;159160// Reserve the anticipated capacity to prevent several reallocations.161result.reserve(std::min(max_length, remaining_bytes_));162for (size_t i = 0; i < max_length && remaining_bytes_ != 0; ++i) {163char next = ConvertUnsignedToSigned<char>(data_ptr_[0]);164Advance(1);165if (next == '\\' && remaining_bytes_ != 0) {166next = ConvertUnsignedToSigned<char>(data_ptr_[0]);167Advance(1);168if (next != '\\')169break;170}171result += next;172}173174result.shrink_to_fit();175return result;176}177178// Returns a std::string of length from 0 to |remaining_bytes_|.179inline std::string FuzzedDataProvider::ConsumeRandomLengthString() {180return ConsumeRandomLengthString(remaining_bytes_);181}182183// Returns a std::string containing all remaining bytes of the input data.184// Prefer using |ConsumeRemainingBytes| unless you actually need a std::string185// object.186inline std::string FuzzedDataProvider::ConsumeRemainingBytesAsString() {187return ConsumeBytesAsString(remaining_bytes_);188}189190// Returns a number in the range [Type's min, Type's max]. The value might191// not be uniformly distributed in the given range. If there's no input data192// left, always returns |min|.193template <typename T> T FuzzedDataProvider::ConsumeIntegral() {194return ConsumeIntegralInRange(std::numeric_limits<T>::min(),195std::numeric_limits<T>::max());196}197198// Returns a number in the range [min, max] by consuming bytes from the199// input data. The value might not be uniformly distributed in the given200// range. If there's no input data left, always returns |min|. |min| must201// be less than or equal to |max|.202template <typename T>203T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) {204static_assert(std::is_integral<T>::value, "An integral type is required.");205static_assert(sizeof(T) <= sizeof(uint64_t), "Unsupported integral type.");206207if (min > max)208abort();209210// Use the biggest type possible to hold the range and the result.211uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(min);212uint64_t result = 0;213size_t offset = 0;214215while (offset < sizeof(T) * CHAR_BIT && (range >> offset) > 0 &&216remaining_bytes_ != 0) {217// Pull bytes off the end of the seed data. Experimentally, this seems to218// allow the fuzzer to more easily explore the input space. This makes219// 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 by221// |ConsumeBytes|. Separating out read lengths makes it easier modify the222// contents of the data that is actually read.223--remaining_bytes_;224result = (result << CHAR_BIT) | data_ptr_[remaining_bytes_];225offset += CHAR_BIT;226}227228// Avoid division by 0, in case |range + 1| results in overflow.229if (range != std::numeric_limits<decltype(range)>::max())230result = result % (range + 1);231232return static_cast<T>(static_cast<uint64_t>(min) + result);233}234235// Returns a floating point value in the range [Type's lowest, Type's max] by236// consuming bytes from the input data. If there's no input data left, always237// returns approximately 0.238template <typename T> T FuzzedDataProvider::ConsumeFloatingPoint() {239return ConsumeFloatingPointInRange<T>(std::numeric_limits<T>::lowest(),240std::numeric_limits<T>::max());241}242243// Returns a floating point value in the given range by consuming bytes from244// the input data. If there's no input data left, returns |min|. Note that245// |min| must be less than or equal to |max|.246template <typename T>247T FuzzedDataProvider::ConsumeFloatingPointInRange(T min, T max) {248if (min > max)249abort();250251T range = .0;252T result = min;253constexpr T zero(.0);254if (max > zero && min < zero && max > min + std::numeric_limits<T>::max()) {255// The diff |max - min| would overflow the given floating point type. Use256// the half of the diff as the range and consume a bool to decide whether257// the result is in the first of the second part of the diff.258range = (max / 2.0) - (min / 2.0);259if (ConsumeBool()) {260result += range;261}262} else {263range = max - min;264}265266return result + range * ConsumeProbability<T>();267}268269// Returns a floating point number in the range [0.0, 1.0]. If there's no270// input data left, always returns 0.271template <typename T> T FuzzedDataProvider::ConsumeProbability() {272static_assert(std::is_floating_point<T>::value,273"A floating point type is required.");274275// Use different integral types for different floating point types in order276// to provide better density of the resulting values.277using IntegralType =278typename std::conditional<(sizeof(T) <= sizeof(uint32_t)), uint32_t,279uint64_t>::type;280281T result = static_cast<T>(ConsumeIntegral<IntegralType>());282result /= static_cast<T>(std::numeric_limits<IntegralType>::max());283return result;284}285286// Reads one byte and returns a bool, or false when no data remains.287inline bool FuzzedDataProvider::ConsumeBool() {288return 1 & ConsumeIntegral<uint8_t>();289}290291// Returns an enum value. The enum must start at 0 and be contiguous. It must292// also contain |kMaxValue| aliased to its largest (inclusive) value. Such as:293// enum class Foo { SomeValue, OtherValue, kMaxValue = OtherValue };294template <typename T> T FuzzedDataProvider::ConsumeEnum() {295static_assert(std::is_enum<T>::value, "|T| must be an enum type.");296return static_cast<T>(297ConsumeIntegralInRange<uint32_t>(0, static_cast<uint32_t>(T::kMaxValue)));298}299300// Returns a copy of the value selected from the given fixed-size |array|.301template <typename T, size_t size>302T FuzzedDataProvider::PickValueInArray(const T (&array)[size]) {303static_assert(size > 0, "The array must be non empty.");304return array[ConsumeIntegralInRange<size_t>(0, size - 1)];305}306307template <typename T, size_t size>308T FuzzedDataProvider::PickValueInArray(const std::array<T, size> &array) {309static_assert(size > 0, "The array must be non empty.");310return array[ConsumeIntegralInRange<size_t>(0, size - 1)];311}312313template <typename T>314T FuzzedDataProvider::PickValueInArray(std::initializer_list<const T> list) {315// TODO(Dor1s): switch to static_assert once C++14 is allowed.316if (!list.size())317abort();318319return *(list.begin() + ConsumeIntegralInRange<size_t>(0, list.size() - 1));320}321322// Writes |num_bytes| of input data to the given destination pointer. If there323// is not enough data left, writes all remaining bytes. Return value is the324// number of bytes written.325// In general, it's better to avoid using this function, but it may be useful326// in cases when it's necessary to fill a certain buffer or object with327// fuzzing data.328inline size_t FuzzedDataProvider::ConsumeData(void *destination,329size_t num_bytes) {330num_bytes = std::min(num_bytes, remaining_bytes_);331CopyAndAdvance(destination, num_bytes);332return num_bytes;333}334335// Private methods.336inline void FuzzedDataProvider::CopyAndAdvance(void *destination,337size_t num_bytes) {338std::memcpy(destination, data_ptr_, num_bytes);339Advance(num_bytes);340}341342inline void FuzzedDataProvider::Advance(size_t num_bytes) {343if (num_bytes > remaining_bytes_)344abort();345346data_ptr_ += num_bytes;347remaining_bytes_ -= num_bytes;348}349350template <typename T>351std::vector<T> FuzzedDataProvider::ConsumeBytes(size_t size, size_t num_bytes) {352static_assert(sizeof(T) == sizeof(uint8_t), "Incompatible data type.");353354// The point of using the size-based constructor below is to increase the355// 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++ and357// 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.360std::vector<T> result(size);361if (size == 0) {362if (num_bytes != 0)363abort();364return result;365}366367CopyAndAdvance(result.data(), num_bytes);368369// Even though |shrink_to_fit| is also implementation specific, we expect it370// to provide an additional assurance in case vector's constructor allocated371// a buffer which is larger than the actual amount of data we put inside it.372result.shrink_to_fit();373return result;374}375376template <typename TS, typename TU>377TS FuzzedDataProvider::ConvertUnsignedToSigned(TU value) {378static_assert(sizeof(TS) == sizeof(TU), "Incompatible data types.");379static_assert(!std::numeric_limits<TU>::is_signed,380"Source type must be unsigned.");381382// TODO(Dor1s): change to `if constexpr` once C++17 becomes mainstream.383if (std::numeric_limits<TS>::is_modulo)384return static_cast<TS>(value);385386// Avoid using implementation-defined unsigned to signed conversions.387// To learn more, see https://stackoverflow.com/questions/13150449.388if (value <= std::numeric_limits<TS>::max()) {389return static_cast<TS>(value);390} else {391constexpr auto TS_min = std::numeric_limits<TS>::min();392return TS_min + static_cast<TS>(value - TS_min);393}394}395396#endif // LLVM_FUZZER_FUZZED_DATA_PROVIDER_H_397398399