• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // A fuzzer for floating-point formatter.
2 // For the license information refer to format.h.
3 
4 #include <cstdint>
5 #include <cstdlib>
6 #include <stdexcept>
7 #include <limits>
8 #include <fmt/format.h>
9 
10 #include "fuzzer-common.h"
11 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)12 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
13   if (size <= sizeof(double) || !std::numeric_limits<double>::is_iec559)
14     return 0;
15 
16   auto value = assign_from_buf<double>(data);
17   auto buffer = fmt::memory_buffer();
18   fmt::format_to(buffer, "{}", value);
19 
20   // Check a round trip.
21   if (std::isnan(value)) {
22     auto nan = std::signbit(value) ? "-nan" : "nan";
23     if (fmt::string_view(buffer.data(), buffer.size()) != nan)
24       throw std::runtime_error("round trip failure");
25     return 0;
26   }
27   buffer.push_back('\0');
28   char* ptr = nullptr;
29   if (std::strtod(buffer.data(), &ptr) != value)
30     throw std::runtime_error("round trip failure");
31   if (ptr + 1 != buffer.end())
32     throw std::runtime_error("unparsed output");
33   return 0;
34 }
35