DataReelDataReelC++ Transition Guide

Examples › Database Examples

database_damaged

C++17 or laterDataReel 6.4.3Portable C++ (tested on Linux)

Legacy: examples_database/damaged/testprog.cpp · Modern: examples_modern/database/damaged/modern.cpp

Modern equivalent of the damaged database file tests. The checks are the legacy ones (zero, tiny and huge block lengths; a file that is not a database file), written with the standard library around gxDatabase:

Legacy calls in this program

LegacyModern C++StandardNotes
strcpy(), strncpy(), memmove() into char arraysstd::string; std::array<char, N> + string_view::copy()C++11 / C++17
clock(), SysTime, GetSystemTime()std::chrono::steady_clock (elapsed), system_clock (calendar)C++11clock() is CPU time, not elapsed time.
gxDatabasekeep gxDatabase: a stack object, errors as exceptions, static_assert(std::is_trivially_copyable_v<Record>)C++17The standard library has no database file; the file format is DataReel's.

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_database/damaged/testprog.cpp 237 lines
#include "gxdlcode.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "gxdbase.h"

#if defined (__UNIX__)
#include <unistd.h>
#include <signal.h>
#include <dirent.h>
#include <sys/resource.h>
#endif

static int failures = 0;

static void check(int ok, const char *what)
{
  printf("%s %s\n", ok ? "PASS" : "FAIL", what);
  if(!ok) failures++;
}

static double seconds()
{
  return (double)clock() / CLOCKS_PER_SEC;
}

const int NUM_OBJECTS = 200; // About 24 KB with rev 'C' blocks
const __ULWORD__ OBJECT_SIZE = 100;

static int make_db(const char *fname, FAU_t *objects)
// A rev 'C' file (block walks and object checksums), returns 1 if
// successful
{
  gxDatabase f;
  if(f.Create(fname, (FAU_t)0, 'C') != gxDBASE_NO_ERROR) return 0;
  char buf[OBJECT_SIZE];
  for(int i = 0; i < NUM_OBJECTS; i++) {
    memset(buf, 'a' + (i % 26), sizeof(buf));
    FAU_t a = f.Alloc(OBJECT_SIZE);
    if(!a || f.Write(buf, OBJECT_SIZE, a) != gxDBASE_NO_ERROR) return 0;
    f.WriteObjectChecksum(a);
    objects[i] = a;
  }
  return f.Close() == gxDBASE_NO_ERROR;
}

static int set_length(const char *fname, FAU_t object, gxUINT32 len)
{
  gxDatabase f;
  if(f.Open(fname) != gxDBASE_NO_ERROR) return 0;
  gxBlockHeader blk;
  FAU_t a = object - f.BlockHeaderSize();
  if(f.Read(&blk, sizeof(blk), a) != gxDBASE_NO_ERROR) return 0;
  blk.block_length = len;
  return f.Write(&blk, sizeof(blk), a) == gxDBASE_NO_ERROR;
}

static long open_files()
// Number of open file descriptors, or -1 if unknown
{
#if defined (__LINUX__)
  DIR *d = opendir("/proc/self/fd");
  if(!d) return -1;
  long n = 0;
  while(readdir(d)) n++;
  closedir(d);
  return n;
#else
  return -1;
#endif
}

static int same_file(const char *a, const char *b)
{
  FILE *fa = fopen(a, "rb"), *fb = fopen(b, "rb");
  int same = (fa && fb);
  while(same) {
    int ca = fgetc(fa), cb = fgetc(fb);
    if(ca != cb) same = 0;
    if(ca == EOF || cb == EOF) break;
  }
  if(fa) fclose(fa);
  if(fb) fclose(fb);
  return same;
}

int main(int argc, char **argv)
{
  // 10/31/2026: testprog --make-damaged file writes a rev 'C' file with
  // a zero block length and a length that wraps the address back, for
  // the db_debug check in run_db_tests.sh
  if(argc == 3 && strcmp(argv[1], "--make-damaged") == 0) {
    FAU_t objs[NUM_OBJECTS];
    if(!make_db(argv[2], objs)) return 1;
    set_length(argv[2], objs[20], 0);
    set_length(argv[2], objs[40], (gxUINT32)0 - (gxUINT32)90);
    set_length(argv[2], objs[60], 3);
    return 0;
  }
#if defined (__UNIX__)
  // AddressSanitizer needs a large address space for its shadow memory
  // and reports huge allocations itself
#if !defined (__SANITIZE_ADDRESS__)
  struct rlimit rl;
  rl.rlim_cur = rl.rlim_max = 1024UL * 1024UL * 1024UL;
  setrlimit(RLIMIT_AS, &rl);
#endif
  alarm(60);
#endif
  FAU_t objects[NUM_OBJECTS];
  const char *fname = "damaged.gxd";
  int created = make_db(fname, objects);
  check(created, "create the test file");
  if(!created) return 1;

  { // Undamaged file: every block counted
    gxDatabase f;
    f.Open(fname, gxDBASE_READONLY);
    check(f.TotalBlocks() == (FAU_t)NUM_OBJECTS, "undamaged file: TotalBlocks() counts every block");
  }

  // zero_length
  make_db(fname, objects);
  set_length(fname, objects[10], 0);
  {
    gxDatabase f;
    f.Open(fname, gxDBASE_READONLY);
    double t0 = seconds();
    FAU_t n = f.TotalBlocks();
    double t = seconds() - t0;
    check(n >= (FAU_t)(NUM_OBJECTS - 1) && n <= (FAU_t)NUM_OBJECTS && t < 2.0,
	  "zero_length: TotalBlocks() ends and skips the damaged block");
    FAU_t a = f.FindFirstObject();
    int walked = 0;
    while(a && walked <= NUM_OBJECTS * 2) {
      walked++;
      a = f.FindFirstObject(a);
    }
    check(walked <= NUM_OBJECTS, "zero_length: an object walk ends");
  }

  // huge_length (from the 7.3 security scan test)
  make_db(fname, objects);
  set_length(fname, objects[10], 0xFFFFFFFF);
  {
    gxDatabase f;
    f.Open(fname, gxDBASE_READONLY);
    double t0 = seconds();
    FAU_t n = f.TotalBlocks();
    double t = seconds() - t0;
    check(t < 2.0 && n <= (FAU_t)NUM_OBJECTS, "huge_length: TotalBlocks() ends on a length past the end of the file");
  }

  // tiny_length
  make_db(fname, objects);
  for(int i = 0; i < NUM_OBJECTS; i += 2) set_length(fname, objects[i], (gxUINT32)(1 + (i % 7)));
  {
    gxDatabase f;
    f.Open(fname, gxDBASE_READONLY);
    double t0 = seconds();
    FAU_t n = f.TotalBlocks();
    double t = seconds() - t0;
    printf("     tiny_length: %ld blocks in %.3f s\n", (long)n, t);
    check(t < 2.0 && n <= (FAU_t)NUM_OBJECTS, "tiny_length: TotalBlocks() takes time in proportion to the file");
  }

  // checksum
  make_db(fname, objects);
  set_length(fname, objects[3], 0x7ffffff0);
  set_length(fname, objects[4], 20); // Shorter than a header and a checksum
  // All bits set but the low ones: with native types on 64-bit systems
  // the length is 64 bits (found by fuzzing 6.3)
  set_length(fname, objects[6], (gxUINT32)0 - (gxUINT32)90);
  {
    gxDatabase f;
    f.Open(fname, gxDBASE_READWRITE);
    __ULWORD__ ocrc = 0, ccrc = 0;
    check(f.ReadObjectChecksum(objects[3], &ocrc, &ccrc) == 0, "checksum: ReadObjectChecksum() refuses a block longer than the file");
    check(f.WriteObjectChecksum(objects[3]) == 0, "checksum: WriteObjectChecksum() refuses a block longer than the file");
    check(f.ReadObjectChecksum(objects[4], &ocrc, &ccrc) == 0, "checksum: a block too short for a checksum is refused");
    check(f.ReadObjectChecksum(objects[6], &ocrc, &ccrc) == 0, "checksum: a length that wraps around is refused");
    check(f.ReadObjectChecksum(objects[5], &ocrc, &ccrc) == 1, "checksum: an undamaged block still checks");
  }

  // wrong_file
  {
    const char *other = "not_a_database.txt";
    const char *copy = "not_a_database.orig";
    FILE *fp = fopen(other, "wb");
    for(int i = 0; i < 4096; i++) fputs("text of another program\n", fp);
    fclose(fp);
    fp = fopen(copy, "wb");
    for(int i = 0; i < 4096; i++) fputs("text of another program\n", fp);
    fclose(fp);
    fp = fopen("short.txt", "wb");
    fputs("short", fp);
    fclose(fp);
    long before = open_files();
    int refused = 1;
    for(int i = 0; i < 300; i++) {
      gxDatabase f;
      if(f.Open(other, gxDBASE_READWRITE) != gxDBASE_WRONG_FILE_TYPE) refused = 0;
      gxDatabase g;
      if(g.Open("short.txt", gxDBASE_READONLY) == gxDBASE_NO_ERROR) refused = 0;
      if(f.IsOpen() || g.IsOpen()) refused = 0;
    }
    gxDatabase reuse;
    for(int i = 0; i < 300; i++) reuse.Open(other, gxDBASE_READONLY);
    long after = open_files();
    check(refused, "wrong_file: Open() refuses a file that is not a database file and leaves it closed");
    check(before < 0 || before == after, "wrong_file: no file handle is left open");
    check(same_file(other, copy), "wrong_file: the other program's file is not changed");
    remove(other);
    remove(copy);
    remove("short.txt");
  }

  // closed_crc
  {
    gxDatabase f;
    check(f.WriteObjectChecksum((FAU_t)1000) == 0, "closed_crc: WriteObjectChecksum() on a closed file returns 0");
  }

  remove(fname);
  if(failures) {
    printf("%d damaged file tests failed\n", failures);
    return 1;
  }
  printf("All damaged file tests passed\n");
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/database/damaged/modern.cpp 125 lines
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <functional>
#include <future>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

#include "gxdbase.h"

namespace fs = std::filesystem;
static int failures = 0;
const int NUM_OBJECTS = 100;
const std::size_t OBJECT_SIZE = 64;

static void check(bool ok, const std::string &what)
{
  std::cout << (ok ? "PASS " : "FAIL ") << what << "\n";
  if(!ok) failures++;
}

// Run a check with a time limit
static bool within(std::chrono::seconds limit, const std::function<bool()> &f)
{
  auto task = std::async(std::launch::async, f);
  if(task.wait_for(limit) == std::future_status::timeout) {
    std::cout << "FAIL a check did not finish in " << limit.count() << " s\n";
    std::_Exit(1);                       // The task cannot be stopped
  }
  return task.get();
}

static std::vector<FAU_t> make_db(const fs::path &fname)
{
  std::vector<FAU_t> objects;
  gxDatabase f;
  if(f.Create(fname.string().c_str(), FAU_t(0), 'C') != gxDBASE_NO_ERROR) return objects;
  for(int i = 0; i < NUM_OBJECTS; i++) {
    std::string buf(OBJECT_SIZE, char('a' + i % 26));
    FAU_t a = f.Alloc(__ULWORD__(OBJECT_SIZE));
    if(!a || f.Write(buf.data(), __ULWORD__(OBJECT_SIZE), a) != gxDBASE_NO_ERROR) return {};
    f.WriteObjectChecksum(a);
    objects.push_back(a);
  }
  return f.Close() == gxDBASE_NO_ERROR ? objects : std::vector<FAU_t>{};
}

static bool set_length(const fs::path &fname, FAU_t object, gxUINT32 len)
{
  gxDatabase f;
  if(f.Open(fname.string().c_str()) != gxDBASE_NO_ERROR) return false;
  gxBlockHeader blk;
  FAU_t a = object - FAU_t(f.BlockHeaderSize());
  if(f.Read(&blk, sizeof blk, a) != gxDBASE_NO_ERROR) return false;
  blk.block_length = len;
  return f.Write(&blk, sizeof blk, a) == gxDBASE_NO_ERROR;
}

static bool same_file(const fs::path &a, const fs::path &b)
{
  std::ifstream fa(a, std::ios::binary), fb(b, std::ios::binary);
  return fa && fb && std::equal(std::istreambuf_iterator<char>(fa), {},
                                std::istreambuf_iterator<char>(fb), {});
}

static bool walk_ends(const fs::path &fname)  // Blocks and objects walks end
{
  gxDatabase f;
  f.Open(fname.string().c_str(), gxDBASE_READONLY);
  FAU_t n = f.TotalBlocks();
  int walked = 0;
  for(FAU_t a = f.FindFirstObject(); a && walked <= NUM_OBJECTS * 2;
      a = f.FindNextObject(a)) walked++;
  return n <= FAU_t(NUM_OBJECTS) && walked <= NUM_OBJECTS;
}

int main()
{
  const fs::path fname = "modern_damaged.gxd";
  auto objects = make_db(fname);
  check(objects.size() == std::size_t(NUM_OBJECTS), "create the test file");
  if(objects.empty()) return 1;
  {
    gxDatabase f;
    f.Open(fname.string().c_str(), gxDBASE_READONLY);
    check(f.TotalBlocks() == FAU_t(NUM_OBJECTS), "undamaged file: every block counted");
  }

  struct Damage { const char *name; gxUINT32 length; };
  for(const Damage &d : {Damage{"zero_length", 0}, Damage{"tiny_length", 3},
                         Damage{"huge_length", gxUINT32(0) - gxUINT32(90)}}) {
    objects = make_db(fname);
    set_length(fname, objects[10], d.length);
    check(within(std::chrono::seconds(10), [&] { return walk_ends(fname); }),
          std::string(d.name) + ": the block and object walks end");
  }

  // wrong_file
  const fs::path other = "modern_not_a_database.txt", copy = "modern_not_a_database.orig";
  for(const auto &p : {other, copy}) {
    std::ofstream out(p, std::ios::binary);
    for(int i = 0; i < 4096; i++) out << "text of another program\n";
  }
  bool refused = true;
  for(int i = 0; i < 50; i++) {
    gxDatabase f;
    if(f.Open(other.string().c_str(), gxDBASE_READWRITE) != gxDBASE_WRONG_FILE_TYPE || f.IsOpen())
      refused = false;
  }
  check(refused, "wrong_file: Open() refuses the file and leaves it closed");
  check(same_file(other, copy), "wrong_file: the other program's file is not changed");

  for(const auto &p : {fname, other, copy}) fs::remove(p);
  std::cout << failures << " failure(s)\n";
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target database_damaged
./build-modern/database_damaged

Output of the modern program

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

PASS create the test file
PASS undamaged file: every block counted
PASS zero_length: the block and object walks end
PASS tiny_length: the block and object walks end
PASS huge_length: the block and object walks end
PASS wrong_file: Open() refuses the file and leaves it closed
PASS wrong_file: the other program's file is not changed
0 failure(s)