DataReelDataReelC++ Transition Guide

Examples › General Examples

general_fuzz_fuzz_text

C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_general/fuzz/fuzz_text.cpp · Modern: examples_modern/general/fuzz/fuzz_text.cpp

Modern equivalent of the libFuzzer targets for the 6.x text code (gxConfig, gxString, Base64). The code under test is the standard library replacement for each: a key=value reader built on std::getline() and std::string_view, string searches and edits on std::string, number parsing with std::from_chars, and a Base64 round trip. The input comes in as a std::string_view over the fuzzer's bytes.

Build as a libFuzzer target (clang): clang++ -std=c++17 -g -O1 -fsanitize=fuzzer,address,undefined \ -DMODERN_LIBFUZZER fuzz_text.cpp -o fuzz_text Without -DMODERN_LIBFUZZER it builds a main() that feeds the target random inputs from std::mt19937 (C++11 <random>), so any compiler can run a quick check.

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
Find(), IFind(), FindLast()find(), a std::search with a case-folding predicate, rfind()C++98Watch out: rfind("") returns size(), where FindLast("") returns -1.
DeleteAt(), InsertAt(), ReplaceAt(), ReplaceString()erase(), insert(), replace(); std::replace for charactersC++98A count past the end is clamped; a position past the end throws std::out_of_range.
Left(), Mid(), Right()substr() on std::string or std::string_viewC++98 / C++17
TrimLeading(), TrimTrailing()find_first_not_of() / find_last_not_of() + substr()C++98
ToUpper(), ToLower()std::transform with std::toupper on unsigned charC++98
Atoi(), Atol(), Atof(), atoi()std::from_chars() into std::optional<T>; std::stoi()C++17Overflow and junk are reported, not turned into 0.
gxsBase64Encode()/Decode()a short RFC 4648 function over std::string_view returning std::optionalC++17No standard Base64.
gxConfigstd::getline() into a std::map; std::optional lookups; std::from_charsC++17A rewrite through a temporary file and rename().

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_general/fuzz/fuzz_text.cpp 99 lines
#include "gxdlcode.h"

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include "gxstring.h"
#include "strutil.h"
#include "gxconfig.h"
#include "gxs_b64.h"

#if defined (FUZZ_CFG)
static void fuzz_cfg(const uint8_t *data, size_t size)
{
  FILE *fp = fopen("fz.cfg", "wb");
  if(!fp) return;
  fwrite(data, 1, size, fp);
  fclose(fp);
  gxConfig cfg("fz.cfg");
  char *v = cfg.GetStrValue("Name");
  if(v) { size_t n = strlen(v); (void)n; }
  cfg.GetIntValue("Size");
  cfg.GetFloatValue("Ratio");
  cfg.GetLongValue("Long");
  cfg.ChangeConfigValue("Name", "value");
  cfg.ChangeConfigValue("NewKey", 42);
}
#endif

#if defined (FUZZ_STR)
static void fuzz_str(const uint8_t *data, size_t size)
{
  if(size < 4) return;
  unsigned a = data[0], b = data[1];
  std::string all((const char *)data + 4, size - 4);
  size_t cut = all.find('\x01');
  std::string s1 = all.substr(0, cut), s2 = (cut == std::string::npos) ? "" : all.substr(cut + 1);
  s1 = std::string(s1.c_str()); // As C strings
  s2 = std::string(s2.c_str());
  gxString g(s1.c_str());
  g.Find(s2.c_str());
  g.IFind(s2.c_str(), a);
  g.FindLast(s2.c_str());
  g.Atoi(); g.Atol(); g.Atof(); g.Atou();
  { gxString t = g; t.ReplaceString(s2.c_str(), "xy"); }
  { gxString t = g; t.FilterString(s2.c_str()); }
  { gxString t = g; t.FilterChar((char)b); t.TrimLeadingSpaces(); t.TrimTrailingSpaces(); }
  { gxString t = g; t.DeleteAfter(s2.c_str()); }
  { gxString t = g; t.DeleteBeforeLastIncluding(s2.c_str()); }
  { gxString t = g; t.DeleteAfterLastIncluding(s2.c_str()); }
  { gxString t = g; t.InsertAt(a, s2.c_str()); t.ReplaceAt(b, s2.c_str()); t.DeleteAt(a, b); }
  { gxString t = g; t.ConvertEscapeSeq('%', 1 + (data[2] % 3)); }
  { gxString t = g; t.ToUpper(); t.ToLower(); t.Cat(s2.c_str()); t.Left(a); t.Right(b); t.Mid(a, b); }
  CaseICmp(s1.c_str(), s2.c_str());
  StringANCompare(s1.c_str(), s2.c_str(), data[3] & 1);
  FindMatch(s1.c_str(), s2.c_str(), data[2] & 1);
  IFindMatch(s1.c_str(), s2.c_str(), data[2] & 1);
  StringToULWORD(s1.c_str());
  StringToULLWORD(s1.c_str());
  StringToLLWORD(s1.c_str());
  gxfind_pattern(s1.data(), (unsigned)s1.size(), s2.data(), (unsigned)s2.size(), a, gxASCII_STRING, data[3] & 2);
  char words[MAXWORDS][MAXWORDLENGTH];
  int numwords = 0;
  parse(s1.c_str(), words, &numwords, (char)b);
}
#endif

#if defined (FUZZ_B64)
static void fuzz_b64(const uint8_t *data, size_t size)
{
  std::string s((const char *)data, size);
  std::string c(s.c_str());
  std::string dec(c.size() + 4, '\0');
  gxsBase64Decode(c.c_str(), &dec[0]);
  std::string enc(gxsCalculateBase64Length((int)size) + 4, '\0');
  gxsBase64Encode(s.data(), &enc[0], (int)size);
  std::string back(enc.size() + 4, '\0');
  gxsBase64Decode(enc.c_str(), &back[0]);
  if(memcmp(back.data(), s.data(), size) != 0) __builtin_trap(); // Round trip
}
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
#if defined (FUZZ_CFG)
  fuzz_cfg(data, size);
#elif defined (FUZZ_STR)
  fuzz_str(data, size);
#elif defined (FUZZ_B64)
  fuzz_b64(data, size);
#else
#error Define FUZZ_CFG, FUZZ_STR or FUZZ_B64
#endif
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/general/fuzz/fuzz_text.cpp 133 lines
#include <charconv>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <map>
#include <optional>
#include <random>
#include <sstream>
#include <string>
#include <string_view>

static std::string_view trim(std::string_view s)
{
  auto b = s.find_first_not_of(" \t\r");
  if(b == std::string_view::npos) return {};
  return s.substr(b, s.find_last_not_of(" \t\r") - b + 1);
}

static void fuzz_cfg(std::string_view in)
{
  std::istringstream ss{std::string(in)};
  std::map<std::string, std::string, std::less<>> values;
  for(std::string line; std::getline(ss, line);) {
    std::string_view v = trim(line);
    if(v.empty() || v[0] == '#') continue;
    auto eq = v.find('=');
    if(eq == std::string_view::npos) continue;
    values[std::string(trim(v.substr(0, eq)))] = std::string(trim(v.substr(eq + 1)));
  }
  for(const auto &kv : values) {
    long long n = 0;
    (void)std::from_chars(kv.second.data(), kv.second.data() + kv.second.size(), n);
    double d = 0;
    (void)std::from_chars(kv.second.data(), kv.second.data() + kv.second.size(), d);
  }
}

static void fuzz_str(std::string_view in)
{
  if(in.empty()) return;
  std::size_t split = std::size_t(static_cast<unsigned char>(in[0])) % in.size();
  std::string s(in.substr(split));
  std::string_view pat = in.substr(0, split);
  for(auto pos = s.find(pat); pos != std::string::npos && !pat.empty();
      pos = s.find(pat, pos + 1)) {}
  (void)s.rfind(pat);
  std::string t = s;
  if(!pat.empty())
    for(std::size_t pos = 0; (pos = t.find(pat, pos)) != std::string::npos;
        pos += 3) t.replace(pos, pat.size(), "abc");
  if(!s.empty()) {
    std::size_t at = split % (s.size() + 1);
    s.insert(at, pat);
    s.erase(at, split);                    // Count past the end is clamped
  }
  unsigned long long u = 0;
  (void)std::from_chars(in.data(), in.data() + in.size(), u, 16);
}

static const char b64[] =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static std::string b64_encode(std::string_view in)
{
  std::string out;
  std::uint32_t acc = 0;
  int bits = 0;
  for(unsigned char c : in) {
    acc = (acc << 8) | c;
    bits += 8;
    while(bits >= 6) { bits -= 6; out += b64[(acc >> bits) & 0x3f]; }
  }
  if(bits) out += b64[(acc << (6 - bits)) & 0x3f];
  while(out.size() % 4) out += '=';
  return out;
}

static std::optional<std::string> b64_decode(std::string_view in)
{
  if(in.size() % 4) return std::nullopt;
  std::string out;
  std::uint32_t acc = 0;
  int bits = 0;
  bool pad = false;
  for(std::size_t i = 0; i < in.size(); i++) {
    if(in[i] == '=') { if(i + 2 < in.size()) return std::nullopt; pad = true; continue; }
    if(pad) return std::nullopt;
    const char *p = std::char_traits<char>::find(b64, 64, in[i]);
    if(!p) return std::nullopt;
    acc = (acc << 6) | std::uint32_t(p - b64);
    bits += 6;
    if(bits >= 8) { bits -= 8; out += char((acc >> bits) & 0xff); }
  }
  return out;
}

static void fuzz_b64(std::string_view in)
{
  if(b64_decode(b64_encode(in)) != std::string(in)) std::abort(); // Round trip
  (void)b64_decode(in);                                           // Any input
}

extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size)
{
  std::string_view in(reinterpret_cast<const char *>(data), size);
  fuzz_cfg(in);
  fuzz_str(in);
  fuzz_b64(in);
  return 0;
}

#if !defined(MODERN_LIBFUZZER)
int main(int argc, char **argv)
{
  int runs = argc > 1 ? std::atoi(argv[1]) : 20000;
  std::mt19937 gen(12345);                         // Repeatable inputs
  std::uniform_int_distribution<int> len(0, 256), byte(0, 255);
  std::string buf;
  for(int i = 0; i < runs; i++) {
    buf.resize(std::size_t(len(gen)));
    for(auto &c : buf) c = char(byte(gen));
    if(i % 3 == 0) buf = "Name = " + std::to_string(i) + "\n#c\nKey=0x" + buf;
    LLVMFuzzerTestOneInput(reinterpret_cast<const std::uint8_t *>(buf.data()),
                           buf.size());
  }
  std::cout << "fuzz_text: " << runs << " random inputs, no failures\n";
  return 0;
}
#endif
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target general_fuzz_fuzz_text
./build-modern/general_fuzz_fuzz_text
# or without CMake:
g++ -std=c++17 -pthread -o general_fuzz_fuzz_text examples_modern/general/fuzz/fuzz_text.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

fuzz_text: 20000 random inputs, no failures