No description
  • C 98.2%
  • CMake 1.8%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Evan Burkey af2b0c8c1c
All checks were successful
test / test (push) Successful in 13s
test / sanitize (push) Successful in 14s
Add EWAD header hash (format v2) and atomic file writes (#3)
## Summary

Two changes ahead of Wayfinder adopting EWAD for game data and save games.

- **EWAD format version 2.** The 8 bytes at header offset 48 hold a header hash: XXH64, seed 0, over the header with the hash field zero, the directory, then the string table, in that order wherever they sit in the file. `wad_view_open` bounds-checks both ranges, checks the hash, then runs the per-entry validation. It reads no lump data. The value is exposed as `WAD_View.archive_hash`. Version 1 is rejected, and all structural checks stay.
- **Atomic file writes.** `wad_write_file` and `wad_write_file_ex` write a uniquely named temporary file beside the target, fsync it, rename it over the target, and fsync the directory. On failure the target keeps its bytes and the temporary file is removed. POSIX-only.

Also updates `README.md`, `docs/spitwad.md`, `docs/WAD Format.md` and the `spitwad.h` comments, and removes `docs/research/`, which described the earlier design.

## Behaviour changes

- `struct WAD_View` gains `archive_hash` as its last field.
- `spitwad.c` no longer compiles on Windows.
- Symlinks are followed: the file they point at is replaced and the link is kept. A dangling symlink returns `SPITWAD_ERR_IO` and creates nothing.
- A target that is a device, FIFO or directory returns `SPITWAD_ERR_IO`. Renaming over `/dev/full` as root would otherwise destroy the node and report success.
- Writing needs write permission on the directory, so a writable file in a read-only directory now fails.
- A replaced file is a new inode: permission bits are kept, but owner, extended attributes and hard links are not.
- A failed directory fsync happens after the rename, so the target then holds the new bytes while the call returns `SPITWAD_ERR_IO`. This is the one exception to the target being untouched on failure, and it is documented.

## Testing

- 40 of 40 tests pass from a clean `SPITWAD_SANITIZE=ON` build on Apple clang 21, and on GCC 15.2 in `alpine:3.24` as root and as non-root with leak detection on.
- `spitwad.c` compiles without warnings under Wayfinder's flags on both compilers.
- New tests: every bit flipped in named, stripped and hand-built archives, where only computed padding offsets may be accepted; a stale hash alone is rejected; opening with lump pages `PROT_NONE`; atomic-write failure, permission and symlink cases.
- The fixture re-stamps the hash after each deliberate corruption. Disabling each validation and atomic-write check on a scratch copy caught 31 of 32 mutants. The survivor is equivalent, since a missing NUL is still rejected by the length check.
- Classic output is byte-identical to master for IWAD, PWAD, WAD2, WAD3 and PACK. The fixture's header hash is pinned from python-xxhash.

## Not verified

- No real power-loss or full-disk test. The write failure path is simulated with `RLIMIT_FSIZE`, and the fsync order was confirmed from an instrumented build.
- The directory fsync failure path has no test.
- Linux was tested on musl under x86_64 emulation, not glibc.
- On macOS `fsync` does not flush the drive's own cache.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #3
2026-11-08 14:52:13 -08:00
.forgejo/workflows Add EWAD format, status codes and embeddable build (#1) 2026-11-08 12:07:09 -08:00
docs Add EWAD header hash (format v2) and atomic file writes (#3) 2026-11-08 14:52:13 -08:00
tests Add EWAD header hash (format v2) and atomic file writes (#3) 2026-11-08 14:52:13 -08:00
.gitignore Redesign EWAD as a hash-indexed, mmap-friendly pack format (#2) 2026-11-08 13:39:14 -08:00
CMakeLists.txt Add EWAD header hash (format v2) and atomic file writes (#3) 2026-11-08 14:52:13 -08:00
DOOM1.WAD init 2024-02-28 08:10:56 -08:00
LICENSE Add EWAD format, status codes and embeddable build (#1) 2026-11-08 12:07:09 -08:00
README.md Add EWAD header hash (format v2) and atomic file writes (#3) 2026-11-08 14:52:13 -08:00
spitwad.c Add EWAD header hash (format v2) and atomic file writes (#3) 2026-11-08 14:52:13 -08:00
spitwad.h Add EWAD header hash (format v2) and atomic file writes (#3) 2026-11-08 14:52:13 -08:00

spitwad

A C library for reading, writing, and manipulating WAD files. The WAD format was created by id Software for DOOM and has since become a staple of game modding. spitwad treats WADs as a general-purpose archive format: use it for your DOOM clone, or package arbitrary data and send it over a network.

Quick Start

cmake -B build
cmake --build build
cd build && ctest
#include <stdio.h>
#include "spitwad.h"

struct WAD wad;
wad_init(&wad, PWAD);
int rc = wad_add_lump(&wad, "GREETING", (const unsigned char *)"hello", 5);
if (rc == SPITWAD_OK)
    rc = wad_write_file(&wad, "hello.wad");
if (rc != SPITWAD_OK)
    puts(wad_status_name(rc));
wad_destroy(&wad);

wad_load_file and wad_load_data initialize the WAD themselves and do not free what it held, so call wad_destroy before reloading a populated WAD. Everything else needs wad_init first. A failed load leaves the WAD exactly as it was.

Using it from another project

add_subdirectory(spitwad)
target_link_libraries(your_target PRIVATE spitwad)

spitwad is a static library with a public include directory. Tests are built, and DOOM1.WAD copied, only when spitwad is the top-level project. Set SPITWAD_SANITIZE=ON to build the library and its tests with ASan and UBSan.

Return codes

The library prints nothing. Every int-returning function returns a status, and wad_status_name gives a status's identifier.

Status Meaning
SPITWAD_OK (0) Success
SPITWAD_ERR_MALFORMED Input is not a valid WAD, including an empty file, its lumps overlap too heavily to copy, or an EWAD header hash or content hash does not match
SPITWAD_ERR_NO_MEMORY Allocation failed
SPITWAD_ERR_NAME_TOO_LONG Name does not fit the WAD's type
SPITWAD_ERR_INVALID_ARGUMENT NULL or out-of-range argument, unknown type, empty EWAD name, unknown EWAD flag, or bad write option
SPITWAD_ERR_IO File could not be opened, sized, read, or written, or a write target is not a regular file
SPITWAD_ERR_NOT_FOUND No lump has that name or key
SPITWAD_ERR_TOO_LARGE Output would go past the 32-bit offset range of a classic type
SPITWAD_ERR_UNSUPPORTED Valid input using a feature spitwad lacks, such as a compressed WAD2 or WAD3 lump, a reserved EWAD flag, or a stripped EWAD loaded into a struct WAD
SPITWAD_ERR_DUPLICATE_NAME Two lumps in an EWAD being written share a name
SPITWAD_ERR_HASH_COLLISION Two EWAD names collide under 64 consecutive seeds. Practically unreachable

Lump names

Lookup and removal act on the first match. Names may repeat, so walk with wad_get_lump to see every lump.

IWAD, PWAD and PACK store 8 bytes per name, WAD2 and WAD3 store 15. wad_add_lump truncates longer names to fit, and lookup and removal truncate the query the same way, so a name finds its lump either way. EWAD names are 1 to SPITWAD_NAME_MAX (255) bytes, wad_add_lump rejects anything outside that range, and the EWAD writer refuses repeated names.

EWAD format

EWAD is a pack format for engines: 64-bit offsets, a directory sorted by a seeded 64-bit XXH64 hash of each name for binary search, lump data aligned for memory mapping, a header hash over all metadata, a content hash per lump, an LZ4 flag, and names in a string table that can be stripped from shipping builds. All integers are little-endian. The full layout and validation rules are in the WAD format page.

Header, 64 bytes:

Offset Type Field
0 4 bytes Signature EWAD
4 u32 Format version, 2
8 u32 Lump count
12 u32 Alignment, a power of two
16 u64 Hash seed
24 u64 Directory offset
32 u64 String table offset
40 u64 String table size, 0 when names are stripped
48 u64 Header hash
56 8 bytes Reserved, zero

Directory entry, 56 bytes, sorted by key:

Offset Type Field
0 u64 Key: XXH64 of the name under the header seed
8 u64 Lump offset, a multiple of the alignment
16 u64 Stored size
24 u64 Raw size, equal to stored size unless the LZ4 flag is set
32 u64 Content hash: XXH64 of the stored bytes, seed 0
40 u32 Type fourcc, chosen by the application
44 u32 Name offset into the string table, 0xFFFFFFFF when stripped
48 u16 Schema version, chosen by the application
50 u16 Flags: bit 0 is EWAD_FLAG_LZ4
52 u32 Reserved, zero

The header hash is XXH64 with seed 0 over the 64-byte header with the hash field treated as zero, then the whole directory, then the whole string table, in that order wherever they sit in the file. It catches corruption, not tampering.

spitwad never compresses or decompresses. A lump flagged LZ4 holds bytes the caller compressed, with raw_size set to the decompressed size, and readers decompress themselves.

Zero-copy reads

A struct WAD copies every lump. For runtime use, wad_view_open validates an EWAD in place, including its header hash, and wad_view_find binary-searches the directory and returns pointers into the buffer. Nothing is allocated, so the buffer can be a memory-mapped file, and lump pointers carry the archive's alignment.

struct WAD_View view;
if (wad_view_open(&view, mapped, mapped_size) == SPITWAD_OK) {
    struct WAD_Entry e;
    if (wad_view_find(&view, "textures/wall01.png", &e) == SPITWAD_OK
        && wad_view_verify(&e) == SPITWAD_OK)
        use(e.data, e.size);
}

wad_view_open reads no lump data, so a damaged lump is found only by wad_view_verify. wad_load_data and wad_load_file check everything.

view.archive_hash is the header hash, usable as the archive's identity, for example recorded in a save game. It covers every key and content hash, so it changes when any lump's bytes change. It is the value stored in the header, so a damaged lump keeps the same archive_hash until wad_view_verify catches it.

wad_write_data_ex takes WAD_WriteOptions for the alignment (default 16), the starting hash seed, and whether to strip names. A stripped archive can still be searched by name through a view, since lookups hash the name, but cannot be loaded into a struct WAD.

Atomic file writes

wad_write_file and wad_write_file_ex write a temporary file in the target's directory, fsync it, rename it over the target, and fsync the directory. Atomic writes are POSIX-only. On failure they return SPITWAD_ERR_IO, the target keeps its previous bytes, and the temporary file is removed. The exception is a failed fsync of the directory, which happens after the rename: the target then holds the new bytes.

An existing target keeps its permission bits, and a new file gets 0666 minus the umask. A symlink is followed, so the file it points at is replaced and the link is kept. A dangling symlink, or a target that is not a regular file, returns SPITWAD_ERR_IO. The full behavior is in the reference documentation.

Known limitations

  • Quake PAK files are misread. A file with the PACK signature is parsed with the classic WAD layout, which is not the real PAK layout.
  • Compressed WAD2 and WAD3 lumps are refused with SPITWAD_ERR_UNSUPPORTED.
  • Atomic file writes are POSIX-only, and spitwad does not build on Windows.

Known issues

  • WAD2 and WAD3 files written by spitwad before commit f6cb20b do not load. Those versions wrote the WAD2 and WAD3 signatures with the classic 12-byte header and 16-byte entries, which is not the real Quake layout. The reader now expects the real 32-byte entries, so every such file fails the directory range check and returns SPITWAD_ERR_MALFORMED from wad_load_data and wad_load_file. Nothing detects the old layout. No test covers it. To fix: in load_classic in spitwad.c, when the type is WAD2 or WAD3 and dir_offset + num_lumps * 32 overruns the input but dir_offset + num_lumps * 16 ends exactly at it, parse the directory with the classic layout instead (a real Quake WAD2 directory always ends with 32-byte entries, so the 16-byte case cannot be mistaken for one). Add a test that builds such a legacy file by hand and loads it, then update docs/WAD Format.md and delete this entry.

Requirements

  • CMake 3.17+
  • C11 compiler
  • Any POSIX platform (Linux, macOS, BSD)

License

MIT. See LICENSE.

Documentation

Full reference documentation