Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbce3467ab | ||
|
|
d7c558dfbf |
No files matched your search
+4
-9
@@ -14,16 +14,11 @@
|
||||
/testdata/
|
||||
/testwork/
|
||||
/testwork-hyper/
|
||||
/lz_rs
|
||||
/rs_test
|
||||
/testwork-rs/
|
||||
/crc16_test
|
||||
/lzply_deep_repair
|
||||
/testwork-deep/
|
||||
# compression experiments (integrated winners only; lzrans/bwt/ppm rejected)
|
||||
# compression experiments (branch experiments/comp)
|
||||
/experiments/corpora/
|
||||
/experiments/rans_tool
|
||||
/experiments/lzrans
|
||||
/experiments/bwt
|
||||
/experiments/ppm
|
||||
/experiments/dict
|
||||
/experiments/bchcheck
|
||||
/testwork-int/
|
||||
/testwork-bench/
|
||||
@@ -3,9 +3,9 @@ CFLAGS = -O2 -Wall -Wextra
|
||||
LDLIBS = -llz
|
||||
PREFIX = /usr/local
|
||||
|
||||
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
|
||||
|
||||
# Shared core: the v5 archive format, the per-entry pipeline
|
||||
# Shared core: the v4 archive format, the per-entry pipeline
|
||||
# (lzip -> BCH), header I/O, scan, and filters. The
|
||||
# command-line tool (lzply), the FUSE filesystem (lzply_mount),
|
||||
# the statistics tool (lzply_stat) and the heal tool (lzply_heal)
|
||||
@@ -87,44 +87,6 @@ lzply_hyper: lzply_hyper.o bch.o sha256.o
|
||||
bch_test: bch.c bch_test.c bch.h bch_polys.h
|
||||
$(CC) $(CFLAGS) -o $@ bch.c bch_test.c
|
||||
|
||||
# Reed-Solomon codec (rs.c) and the LZRS v1 archive layer
|
||||
# (lzrs_lib.c: LZRS entry encode/decode + header I/O + scan).
|
||||
# lz_rs links both plus the shared v4 core (liblzply.a).
|
||||
rs.o: rs.c rs.h
|
||||
$(CC) $(CFLAGS) -c -o $@ rs.c
|
||||
|
||||
lzrs_lib.o: lzrs_lib.c lzrs_lib.h lzply_lib.h rs.h bch.h sha256.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzrs_lib.c
|
||||
|
||||
liblzrs.a: lzrs_lib.o rs.o
|
||||
ar rcs $@ $^
|
||||
|
||||
lz_rs.o: lz_rs.c lzrs_lib.h lzply_lib.h bch.h bch_polys.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lz_rs.c
|
||||
|
||||
lz_rs: lz_rs.o liblzrs.a liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a liblzply.a $(LDLIBS)
|
||||
|
||||
rs_test: rs.c rs_test.c rs.h
|
||||
$(CC) $(CFLAGS) -o $@ rs.c rs_test.c
|
||||
|
||||
# CRC-16/CCITT-FALSE unit test (vectors + cross-checks). Links the
|
||||
# shared core for crc16_of.
|
||||
crc16_test: crc16_test.c liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ crc16_test.c liblzply.a $(LDLIBS)
|
||||
|
||||
# Deep repair: Chase / list decoding past t (bch.c) + the escalating
|
||||
# ladder (deep_repair.c) + the lzply_deep_repair CLI. Links both
|
||||
# archive layers (LZPL v5 + LZRS v1).
|
||||
deep_repair.o: deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h rs.h sha256.h
|
||||
$(CC) $(CFLAGS) -c -o $@ deep_repair.c
|
||||
|
||||
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_deep_repair.c
|
||||
|
||||
lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(LDLIBS)
|
||||
|
||||
# bch_polys.h is generated by gen_bch_polys.py from the rssearch data
|
||||
# (~/workspace/rssearch/polys.txt + finds.txt) and checked in; it is
|
||||
# NOT rebuilt by make. Regenerate manually after a re-crawl with:
|
||||
@@ -145,51 +107,22 @@ lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a
|
||||
testdata:
|
||||
@if [ ! -d testdata/mixed ]; then ./tests/make_testdata.sh; fi
|
||||
|
||||
test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
test: testdata bch_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
|
||||
./bch_test
|
||||
./rs_test
|
||||
./crc16_test
|
||||
if [ -x ./tests/run_rs_tests.sh ]; then \
|
||||
./tests/run_rs_tests.sh ./lz_rs; \
|
||||
elif [ -x ../tests/run_rs_tests.sh ]; then \
|
||||
../tests/run_rs_tests.sh ./lz_rs; \
|
||||
else echo "run_rs_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_tests.sh ]; then \
|
||||
./tests/run_tests.sh ./lzply; \
|
||||
elif [ -x ../tests/run_tests.sh ]; then \
|
||||
../tests/run_tests.sh ./lzply; \
|
||||
else echo "run_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_deep_repair_tests.sh ]; then \
|
||||
./tests/run_deep_repair_tests.sh ./lzply_deep_repair ./lzply ./lz_rs; \
|
||||
elif [ -x ../tests/run_deep_repair_tests.sh ]; then \
|
||||
../tests/run_deep_repair_tests.sh ./lzply_deep_repair ./lzply ./lz_rs; \
|
||||
else echo "run_deep_repair_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_hyper_tests.sh ]; then \
|
||||
./tests/run_hyper_tests.sh ./lzply_hyper; \
|
||||
elif [ -x ../tests/run_hyper_tests.sh ]; then \
|
||||
../tests/run_hyper_tests.sh ./lzply_hyper; \
|
||||
else echo "run_hyper_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_integration_tests.sh ]; then \
|
||||
./tests/run_integration_tests.sh; \
|
||||
elif [ -x ../tests/run_integration_tests.sh ]; then \
|
||||
../tests/run_integration_tests.sh; \
|
||||
else echo "run_integration_tests.sh not found"; exit 1; fi
|
||||
|
||||
# Integrated experiment winners (docs/INTEGRATION.md): the ECC harness
|
||||
# (interleave d64, small-block BCH, LDPC r90) and the compression
|
||||
# prototypes (rANS core, dict transform). Not part of `all`: the archive
|
||||
# format is unchanged (LZPL v5); these are standalone tools.
|
||||
exp:
|
||||
$(MAKE) -C exp bench ldpc_diag pass2_diag
|
||||
|
||||
experiments:
|
||||
$(MAKE) -C experiments
|
||||
|
||||
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
|
||||
mkdir -p $(PREFIX)/bin
|
||||
install -m 755 lzply $(PREFIX)/bin/lzply
|
||||
install -m 755 lz_rs $(PREFIX)/bin/lz_rs
|
||||
install -m 755 lzply_deep_repair $(PREFIX)/bin/lzply_deep_repair
|
||||
install -m 755 lzply_mount $(PREFIX)/bin/lzply_mount
|
||||
install -m 755 lzply_stat $(PREFIX)/bin/lzply_stat
|
||||
install -m 755 lzply_heal $(PREFIX)/bin/lzply_heal
|
||||
@@ -199,6 +132,6 @@ install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply
|
||||
install -m 755 mount.lzply /sbin/mount.lzply
|
||||
|
||||
clean:
|
||||
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test *.o liblzply.a liblzrs.a
|
||||
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper bch_test *.o liblzply.a
|
||||
|
||||
.PHONY: all test install clean exp experiments
|
||||
.PHONY: all test install clean
|
||||
@@ -11,7 +11,7 @@ One archive file (like zip) holding many entries. Every entry is an
|
||||
independent byte stream:
|
||||
|
||||
```
|
||||
compress -> BCH encode (on write, v5)
|
||||
compress -> BCH encode (on write, v4)
|
||||
BCH-decode -> decompress (on read)
|
||||
```
|
||||
|
||||
@@ -62,9 +62,6 @@ SHA-256 implementation (`sha256.c`).
|
||||
* **`lzply`** — the archiver. Create, extract, test, list, inspect
|
||||
(`-i`), tree (`-tr`), append (`-a`), date filters, store mode.
|
||||
The core of the repo.
|
||||
* **`lz_rs`** — the archiver with Reed-Solomon on top: the same
|
||||
modes as `lzply`, plus `-r <0..4>` for the RS level, writing
|
||||
the LZRS v1 format (see `docs/lzrs-format.md`). Default `-r 2`.
|
||||
* **`lzply_mount`** — mount a `.lzply` archive as a writable
|
||||
filesystem (FUSE). `mount -t lzply` works too.
|
||||
* **`lzply_stat`** — statistics for an archive or a mount point:
|
||||
@@ -113,28 +110,24 @@ Full write-up, including the prior-art check and the per-length
|
||||
tables:
|
||||
https://www.lzply.com/reed-solomon-is-leaving-40-of-your-parity-on-the-table-i-searched-16-377-payload-lengths-and-found-97-612-codes-that-beat-it-all-58-polynomials-full-source/
|
||||
|
||||
## Format (v5; a single format, all integers little-endian)
|
||||
## Format (v4; a single format, all integers little-endian)
|
||||
|
||||
```
|
||||
global header (16 bytes):
|
||||
magic "LZPL", version u8 (5), flags u8, entry_count u32, reserved u64
|
||||
magic "LZPL", version u8 (4), flags u8, entry_count u32, reserved u64
|
||||
entries, each:
|
||||
u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
u32 mode, u64 mtime, u32 header_crc32,
|
||||
path[path_len], data[stored_size]
|
||||
end marker: u16 path_len == 0
|
||||
```
|
||||
|
||||
`header_crc32` covers the 76 bytes before it. `blob_size` is the
|
||||
`header_crc32` covers the 74 bytes before it. `blob_size` is the
|
||||
length of the compressed (or, for a stored entry, raw) stream
|
||||
before error-correction
|
||||
parity was added. `mtime` is the source's modification time in
|
||||
seconds since the epoch (UTC). `crc16` is CRC-16/CCITT-FALSE
|
||||
(poly 0x1021, init 0xFFFF, no reflection, xorout 0) of the blob;
|
||||
writers compute and store it, readers verify it after
|
||||
error-correction decoding and before decompression, and a mismatch
|
||||
is a clean failure, never a misdecode. Level is the lzip level (1..9) of
|
||||
seconds since the epoch (UTC). Level is the lzip level (1..9) of
|
||||
the blob, or 0 for a stored (uncompressed) entry. Flags: bit 0 is
|
||||
unused (it was used
|
||||
by v3), bit 1 =
|
||||
@@ -145,10 +138,8 @@ parent, so `lzply -c photos/` stores `photos/...` and restores the
|
||||
tree on extract. Entry paths containing `..` or starting with `/`
|
||||
are rejected on extract.
|
||||
|
||||
There is no legacy support: v1 (Reed-Solomon), v2, v3, and v4
|
||||
archives
|
||||
are not readable (v3 had AES-256-GCM encryption, removed in v4;
|
||||
v4 predates the CRC16 migration to v5),
|
||||
There is no legacy support: v1 (Reed-Solomon), v2, and v3 archives
|
||||
are not readable (v3 had AES-256-GCM encryption, removed in v4),
|
||||
and neither is any archive with an old magic (`LZRS`
|
||||
or `LZBC`) — the magic is now `LZPL`, and old magics are rejected
|
||||
outright. The format was never used anywhere yet, so it changes
|
||||
@@ -162,91 +153,13 @@ polynomial and checks it byte-identical to `polys.txt`, so the
|
||||
embedded table is verified, not just copied. Regenerate with
|
||||
`python3 gen_bch_polys.py` (or `make bch_polys.h`).
|
||||
|
||||
## lz_rs — lzip + BCH + Reed-Solomon
|
||||
|
||||
`lz_rs` is `lzply` plus a Reed-Solomon layer, in its own format
|
||||
(LZRS v1, magic `LZRS`). The pipeline per entry is lzip compress
|
||||
-> BCH encode -> RS encode, decoded in reverse, with the SHA-256
|
||||
check as the oracle for the whole stack. RS is the outer layer
|
||||
because it corrects whole-byte and burst errors — up to 16 byte
|
||||
errors per 255-byte block at `-r 4` — while BCH stays responsible
|
||||
for scattered bit errors. RS(255, 255-p) over GF(2^8), primitive
|
||||
polynomial `0x11D`, primitive element 2, first consecutive root 0.
|
||||
|
||||
`-r <0..4>` selects the parity per block: 0 = none, 1 -> 8, 2 -> 16,
|
||||
3 -> 24, 4 -> 32 symbols, correcting 0, 4, 8, 12, 16 byte errors
|
||||
per block. Default `-r 2`. `-r 0` behaves like plain lzply: the
|
||||
stored bytes are byte-identical to `lzply -e 0` for the same input.
|
||||
The LZRS v1 entry header is 82 bytes (the v5 layout plus
|
||||
`bch_poly_id` before the header CRC); `crc16` is CRC-16/CCITT-FALSE
|
||||
of the blob, computed by writers and verified by readers (see
|
||||
`docs/lzrs-format.md`). Full design, format, benchmarks and
|
||||
tests: `docs/lzrs-format.md`. `make test` runs `rs_test`
|
||||
(6,243 checks) and `tests/run_rs_tests.sh` (59 checks).
|
||||
|
||||
`lz_rs` rejects lzply v4 archives (they predate the CRC16
|
||||
migration) and `lzply` rejects `.lzrs`
|
||||
archives, in both directions. There is no legacy support: LZRS v1
|
||||
is the only LZRS format.
|
||||
|
||||
## Deep repair — past the BCH limit
|
||||
|
||||
`lzply_deep_repair` recovers entries whose bit errors exceed the
|
||||
BCH correction limit t, in escalating levels, reporting per-level
|
||||
timing ("time of arrival": how long each level took and at which
|
||||
level the repair landed):
|
||||
|
||||
```
|
||||
lzply_deep_repair [-l max-level 0..3] [--time-budget seconds] [-v]
|
||||
[-o outdir] [--entry name] archive
|
||||
```
|
||||
|
||||
- L0: standard decode to t.
|
||||
- L1: Chase-1 — single-bit trial flips (suspects first, then an
|
||||
exhaustive scan). Recovers t+1 essentially always: flipping any
|
||||
one true error leaves t errors, which Berlekamp-Massey corrects.
|
||||
Measured 10/10 at t+1 on 512-byte blocks (t=8), 5/5 on 2 KiB
|
||||
blocks, in 0.03–0.28 s.
|
||||
- L2: Chase-2 — two-bit trial flips over a bounded first-element
|
||||
list (suspects, then a positional prefix, at most 128 entries)
|
||||
paired with every position: at most 128·nbits trials, plus a
|
||||
wall-clock deadline. Measured 3/10 at t+2 on 512-byte blocks
|
||||
(t=8), ~3.9 s each; the rate scales with the list size, roughly
|
||||
1 − (1 − (t+2)/nbits)^128.
|
||||
- L3: cross-block list decoding — two failing blocks varied at
|
||||
once from retained per-block candidate pools (at most 256 blob
|
||||
tries). Lands when each of two blocks holds its true data in
|
||||
the pool but neither single-block variation passes the CRC.
|
||||
|
||||
The CRC16 is the oracle: every beyond-t candidate is CRC-verified
|
||||
before acceptance (then decompressed and SHA-256-checked); the
|
||||
tool reports candidates tried, CRC rejections, and the accepted
|
||||
repair. Expected residual false-accept is ~2^-16 per candidate.
|
||||
Measured across the corruption matrix: 1,162 candidates
|
||||
CRC-checked, 1,024 rejected by CRC, 0 false accepts.
|
||||
|
||||
Limits, measured honestly: Chase scans are O(nbits) trials at
|
||||
~7,800 trials/s on m=22 blocks (a full scan of a 524 KiB block
|
||||
takes ~9 minutes), so beyond-t repair of large blocks is bounded
|
||||
by the time budget (default 120 s per entry) and reports partial
|
||||
coverage rather than pretending. Two bugs found by measurement
|
||||
and fixed: the trial flip was not applied to the reconstructed
|
||||
word (Chase-1 recovered 0/20 before the fix), and L1 pooled
|
||||
candidates before trying them, truncating the list before the
|
||||
genuine candidate arrived (a 600 KiB file with 9 errors in one
|
||||
block failed at a 60 s budget before the fix; it recovers after
|
||||
it). Full design, bounds, and measured numbers:
|
||||
`docs/deep-repair.md`. Tests: `tests/run_deep_repair_tests.sh`
|
||||
(round-trips, old-format rejection, corruption matrix,
|
||||
false-accept measurement).
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
apt install build-essential liblz-dev # Debian/Ubuntu
|
||||
make # produces ./lzply, ./lz_rs, ./lzply_mount, ./lzply_stat, ./lzply_heal, ./lzply_check, ./lzply_refresh, ./lzply_deep_repair
|
||||
make test # BCH + RS + CRC16 unit tests + full archive test suites (lzply + lz_rs + deep repair)
|
||||
sudo make install # /usr/local/bin/lzply* (including lz_rs), /sbin/mount.lzply
|
||||
make # produces ./lzply, ./lzply_mount, ./lzply_stat, ./lzply_heal, ./lzply_check, ./lzply_refresh
|
||||
make test # BCH unit tests + full archive test suite
|
||||
sudo make install # /usr/local/bin/lzply*, /sbin/mount.lzply
|
||||
```
|
||||
|
||||
## Usage
|
||||
@@ -438,35 +351,7 @@ Set `LZPLY_TEST_ROOT` to point the suite at a different tree root
|
||||
(default: the parent of the `tests/` directory, so it works both
|
||||
from the repo layout `~/workspace/lzply` and from `/opt/lzply/src`).
|
||||
|
||||
## Integrated experiments — interleaving, small-block BCH, LDPC, dict
|
||||
|
||||
The open-ended research branches (`experiments/baseline`,
|
||||
`experiments/ecc`, `experiments/comp`) were merged onto current main
|
||||
on `experiments/integration`. Four winners, measured numbers only,
|
||||
full write-up in `docs/INTEGRATION.md`:
|
||||
|
||||
* **Byte interleaving d64 over small-block BCH** (`exp/`): zero extra
|
||||
parity; a 256 B burst that kills uninterleaved BCH (0.00 recovery)
|
||||
is recovered 1.00. Same 5.40% overhead as the BCH underneath.
|
||||
* **Small-block BCH, 1 KiB blocks** (`exp/`): `bch1k-t32` survives
|
||||
BER 1e-3 at 1.00 where as-shipped `bch-t32` scores 0.00, at 5.40%
|
||||
overhead vs 0.12%.
|
||||
* **Regular LDPC r90** (`exp/`): 1.00 at BER 1e-3, 0.97 at 3e-3
|
||||
where `bch1k-t32` scores 0.01; 10.94% overhead, ~4x slower decode.
|
||||
* **Dictionary transform, code-only** (`experiments/`): -2.1% vs
|
||||
plain lzip -6 on code; worse everywhere else, so opt-in only.
|
||||
The rANS core is kept as supporting infrastructure.
|
||||
|
||||
Rejected with numbers (code not carried over): polar SC (0.00 at
|
||||
BER 1e-3), UEP (whole-file recovery dominated by the weak tier),
|
||||
LZ77+rANS, BWT, and PPM order-2 — none beats lzip on ratio.
|
||||
|
||||
The archive format is unchanged (LZPL v5); the winners are
|
||||
standalone tools, built with `make exp` / `make experiments` and
|
||||
smoke-tested by `tests/run_integration_tests.sh` as part of
|
||||
`make test`.
|
||||
|
||||
## Limitations (v5)
|
||||
## Limitations (v4)
|
||||
|
||||
* Whole files are buffered in memory (compress, BCH, and
|
||||
the archive entry). A 50 MiB file is fine; multi-gigabyte files
|
||||
|
||||
@@ -39,7 +39,6 @@
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "bch.h"
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -319,22 +318,15 @@ static uint32_t gf_pow_slow(uint32_t a, uint32_t e, uint32_t P, int m)
|
||||
|
||||
/* (gf_inv via the log/exp tables is used instead; see gf_div_tab.) */
|
||||
|
||||
/* log/exp tables, cached per m (single slot; lzply is single-threaded).
|
||||
* For large m the tables (2^m entries each) stop fitting in cache and
|
||||
* random table lookups cost more than the shift-and-xor multiply, so
|
||||
* gf_mul_tab dispatches to gf_mul_slow when slow is set (m >= 17,
|
||||
* tables >= 1 MiB). Both compute the same field multiplication;
|
||||
* only the speed differs. */
|
||||
/* log/exp tables, cached per m (single slot; lzply is single-threaded). */
|
||||
typedef struct {
|
||||
int m;
|
||||
uint32_t N; /* 2^m - 1 */
|
||||
uint32_t P; /* primitive polynomial for this m */
|
||||
int slow; /* use gf_mul_slow instead of the tables */
|
||||
uint32_t *exp; /* exp[i] = alpha^i, i = 0..N-1 */
|
||||
uint32_t *log; /* log[v] = i with alpha^i = v, v = 1..N-1 */
|
||||
} gf_tables_t;
|
||||
|
||||
static gf_tables_t gf_cache = { 0, 0, 0, 0, NULL, NULL };
|
||||
static gf_tables_t gf_cache = { 0, 0, NULL, NULL };
|
||||
|
||||
static const gf_tables_t *gf_tables_for(int m)
|
||||
{
|
||||
@@ -343,8 +335,6 @@ static const gf_tables_t *gf_tables_for(int m)
|
||||
free(gf_cache.exp);
|
||||
free(gf_cache.log);
|
||||
gf_cache.m = 0;
|
||||
gf_cache.P = 0;
|
||||
gf_cache.slow = 0;
|
||||
gf_cache.exp = NULL;
|
||||
gf_cache.log = NULL;
|
||||
uint32_t P = bch_prim_poly[m];
|
||||
@@ -367,8 +357,6 @@ static const gf_tables_t *gf_tables_for(int m)
|
||||
log[0] = 0;
|
||||
gf_cache.m = m;
|
||||
gf_cache.N = N;
|
||||
gf_cache.P = P;
|
||||
gf_cache.slow = (m >= 17);
|
||||
gf_cache.exp = exp;
|
||||
gf_cache.log = log;
|
||||
return &gf_cache;
|
||||
@@ -378,8 +366,6 @@ static uint32_t gf_mul_tab(uint32_t a, uint32_t b, const gf_tables_t *t)
|
||||
{
|
||||
if (!a || !b)
|
||||
return 0;
|
||||
if (t->slow)
|
||||
return gf_mul_slow(a, b, t->P, t->m);
|
||||
uint32_t s = t->log[a] + t->log[b];
|
||||
if (s >= t->N)
|
||||
s -= t->N;
|
||||
@@ -1019,789 +1005,3 @@ int bch_decode_candidates(const uint8_t *in, size_t len, size_t orig_len,
|
||||
free(bslen);
|
||||
return nc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Deep repair: Chase / list decoding past t (see bch.h). */
|
||||
/* */
|
||||
/* A trial flip at bit position p changes the syndrome by the */
|
||||
/* column col(p): S_j ^= alpha^(j*(n-1-p)). A trial is GOOD iff the */
|
||||
/* BM locator for the flipped syndrome splits completely over */
|
||||
/* GF(2^m) with all roots at in-range positions and the corrected */
|
||||
/* word has zero remainder. The splitting test (gcd with */
|
||||
/* x^(2^m) - x) costs O(m*t^2) per trial versus O(n*t) for Chien, */
|
||||
/* so it filters trials cheaply and Chien runs only for survivors. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
double bch_now(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
||||
}
|
||||
|
||||
/* Berlekamp-Massey on S_1..S_2t, using the log/exp tables. Same
|
||||
* arithmetic as berlekamp_massey (exact same result), faster.
|
||||
* Returns the degree L and fills lambda[0..L] (lambda[0]=1). */
|
||||
static int berlekamp_massey_tab(const uint32_t *S, int t, int m,
|
||||
const gf_tables_t *tab, uint32_t *lambda)
|
||||
{
|
||||
(void)m; /* the field is fully described by tab */
|
||||
uint32_t C[33], B[33], T[33];
|
||||
for (int i = 0; i <= 32; i++)
|
||||
C[i] = B[i] = 0;
|
||||
C[0] = B[0] = 1;
|
||||
int L = 0, shift = 1;
|
||||
uint32_t b = 1;
|
||||
for (int n = 0; n < 2 * t; n++) {
|
||||
/* discrepancy d = S_{n+1} + sum_{i=1..L} C_i * S_{n+1-i} */
|
||||
uint32_t d = S[n];
|
||||
for (int i = 1; i <= L; i++) {
|
||||
if (C[i] && n - i >= 0)
|
||||
d ^= gf_mul_tab(C[i], S[n - i], tab);
|
||||
}
|
||||
if (d == 0) {
|
||||
shift++;
|
||||
continue;
|
||||
}
|
||||
memcpy(T, C, sizeof(T));
|
||||
uint32_t coef = gf_div_tab(d, b, tab);
|
||||
/* C = C + coef * x^shift * B */
|
||||
for (int i = 0; i <= 32 - shift; i++) {
|
||||
if (B[i])
|
||||
C[i + shift] ^= gf_mul_tab(coef, B[i], tab);
|
||||
}
|
||||
if (2 * L <= n) {
|
||||
L = n + 1 - L;
|
||||
memcpy(B, T, sizeof(B));
|
||||
b = d;
|
||||
shift = 1;
|
||||
} else {
|
||||
shift++;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i <= L; i++)
|
||||
lambda[i] = C[i];
|
||||
return L;
|
||||
}
|
||||
|
||||
/* Degree of a polynomial (highest nonzero coefficient), -1 if zero.
|
||||
* Coefficients are co[0..maxd]. */
|
||||
static int poly_deg(const uint32_t *a, int maxd)
|
||||
{
|
||||
for (int i = maxd; i >= 0; i--)
|
||||
if (a[i])
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Reduce prod (degree <= 2L-2) modulo the monic polynomial mod[0..L]
|
||||
* (mod[L] == 1, only mod[0..L-1] are read). In place. */
|
||||
static void poly_reduce(uint32_t *prod, int L, const uint32_t *mod,
|
||||
const gf_tables_t *tab)
|
||||
{
|
||||
for (int k = 2 * L - 2; k >= L; k--) {
|
||||
uint32_t c = prod[k];
|
||||
if (!c)
|
||||
continue;
|
||||
prod[k] = 0;
|
||||
for (int j = 0; j < L; j++)
|
||||
if (mod[j])
|
||||
prod[k - L + j] ^= gf_mul_tab(c, mod[j], tab);
|
||||
}
|
||||
}
|
||||
|
||||
/* Square a (degree < L) modulo mod: in characteristic 2,
|
||||
* (sum a_i x^i)^2 = sum a_i^2 x^{2i}. out[0..L-1]. */
|
||||
static void poly_square_mod(const uint32_t *a, int L, const uint32_t *mod,
|
||||
const gf_tables_t *tab, uint32_t *out)
|
||||
{
|
||||
uint32_t prod[65];
|
||||
memset(prod, 0, sizeof prod);
|
||||
for (int i = 0; i < L; i++)
|
||||
if (a[i])
|
||||
prod[2 * i] ^= gf_mul_tab(a[i], a[i], tab);
|
||||
poly_reduce(prod, L, mod, tab);
|
||||
memset(out, 0, (size_t)33 * sizeof(uint32_t));
|
||||
memcpy(out, prod, (size_t)L * sizeof(uint32_t));
|
||||
}
|
||||
|
||||
/* Remainder of a (degree da) divided by b (degree db). out gets the
|
||||
* remainder (degree < db). */
|
||||
static void poly_rem(const uint32_t *a, int da, const uint32_t *b, int db,
|
||||
const gf_tables_t *tab, uint32_t *out)
|
||||
{
|
||||
uint32_t r[33];
|
||||
memset(r, 0, sizeof r);
|
||||
memcpy(r, a, (size_t)(da + 1) * sizeof(uint32_t));
|
||||
for (int i = da; i >= db; i--) {
|
||||
uint32_t f;
|
||||
if (!r[i])
|
||||
continue;
|
||||
f = gf_div_tab(r[i], b[db], tab);
|
||||
r[i] = 0;
|
||||
for (int j = 0; j < db; j++)
|
||||
if (b[j])
|
||||
r[i - db + j] ^= gf_mul_tab(f, b[j], tab);
|
||||
}
|
||||
memset(out, 0, (size_t)33 * sizeof(uint32_t));
|
||||
memcpy(out, r, (size_t)(db > 0 ? db : 0) * sizeof(uint32_t));
|
||||
}
|
||||
|
||||
/* gcd of a (degree da) and b (degree db). Returns the degree in
|
||||
* *dout, coefficients in out[0..dout]. */
|
||||
static void poly_gcd(const uint32_t *a, int da, const uint32_t *b, int db,
|
||||
const gf_tables_t *tab, uint32_t *out, int *dout)
|
||||
{
|
||||
uint32_t x[33], y[33], r[33];
|
||||
int dx, dy;
|
||||
memset(x, 0, sizeof x);
|
||||
memset(y, 0, sizeof y);
|
||||
memcpy(x, a, (size_t)(da + 1) * sizeof(uint32_t));
|
||||
memcpy(y, b, (size_t)(db + 1) * sizeof(uint32_t));
|
||||
dx = da;
|
||||
dy = db;
|
||||
for (;;) {
|
||||
int dr;
|
||||
if (dy < 0) { /* y is zero: gcd is x */
|
||||
memcpy(out, x, sizeof(uint32_t) * (size_t)(dx + 1));
|
||||
*dout = dx;
|
||||
return;
|
||||
}
|
||||
if (dy == 0) { /* y is a nonzero constant: gcd is 1 */
|
||||
out[0] = 1;
|
||||
*dout = 0;
|
||||
return;
|
||||
}
|
||||
if (dx < dy) { /* keep deg x >= deg y */
|
||||
uint32_t t[33];
|
||||
int td = dx;
|
||||
memcpy(t, x, sizeof t);
|
||||
memcpy(x, y, sizeof x);
|
||||
dx = dy;
|
||||
memcpy(y, t, sizeof y);
|
||||
dy = td;
|
||||
}
|
||||
poly_rem(x, dx, y, dy, tab, r);
|
||||
dr = poly_deg(r, dy - 1);
|
||||
if (dr < 0) { /* y divides x: gcd is y */
|
||||
memcpy(out, y, sizeof(uint32_t) * (size_t)(dy + 1));
|
||||
*dout = dy;
|
||||
return;
|
||||
}
|
||||
memcpy(x, y, sizeof x);
|
||||
dx = dy;
|
||||
memcpy(y, r, sizeof y);
|
||||
dy = dr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Does the monic locator lambda[0..L] (lambda[L] == 1) split
|
||||
* completely into L distinct linear factors over GF(2^m)?
|
||||
* Computes g = gcd(lambda, x^(2^m) - x); splits iff deg g == L.
|
||||
* x^(2^m) mod lambda comes from m repeated squarings of x. */
|
||||
static int lambda_splits(const uint32_t *lambda, int L, int m,
|
||||
const gf_tables_t *tab)
|
||||
{
|
||||
uint32_t cur[33], nxt[33], h[33], g[33];
|
||||
int dg, dh;
|
||||
if (L <= 1)
|
||||
return 1; /* degree 0/1 always splits */
|
||||
/* cur = x mod lambda */
|
||||
memset(cur, 0, sizeof cur);
|
||||
cur[1] = 1;
|
||||
for (int i = 0; i < m; i++) {
|
||||
poly_square_mod(cur, L, lambda, tab, nxt);
|
||||
memcpy(cur, nxt, sizeof cur);
|
||||
}
|
||||
/* h = cur - x = x^(2^m) - x mod lambda */
|
||||
memcpy(h, cur, sizeof h);
|
||||
h[1] ^= 1;
|
||||
dh = poly_deg(h, L - 1);
|
||||
poly_gcd(lambda, L, h, dh, tab, g, &dg);
|
||||
return dg == L;
|
||||
}
|
||||
|
||||
/* Chien search: evaluate lambda at x_p = alpha^(p-(n-1)) for
|
||||
* p = 0..nbits-1; record the positions where it vanishes (up to
|
||||
* maxpos). Returns the number found. lambda[0..L]. */
|
||||
static int chien_positions(const uint32_t *lambda, int L, size_t nbits,
|
||||
const gf_tables_t *tab, size_t *positions,
|
||||
int maxpos)
|
||||
{
|
||||
uint32_t N = tab->N;
|
||||
uint32_t x0 = tab->exp[(N - (nbits - 1) % N) % N]; /* alpha^-(n-1) */
|
||||
uint32_t v[33];
|
||||
uint32_t ajpow[33];
|
||||
uint32_t xp = 1;
|
||||
int found = 0;
|
||||
for (int j = 0; j <= L; j++) {
|
||||
/* v[j] = lambda[j] * x0^j */
|
||||
v[j] = lambda[j] ? gf_mul_tab(lambda[j], xp, tab) : 0;
|
||||
xp = gf_mul_tab(xp, x0, tab);
|
||||
ajpow[j] = tab->exp[j % N];
|
||||
}
|
||||
for (size_t p = 0; p < nbits && found < L; p++) {
|
||||
uint32_t sum = 0;
|
||||
for (int j = 0; j <= L; j++)
|
||||
sum ^= v[j];
|
||||
if (sum == 0) {
|
||||
if (found < maxpos)
|
||||
positions[found] = p;
|
||||
found++;
|
||||
}
|
||||
/* advance to p+1: v[j] *= alpha^j */
|
||||
for (int j = 1; j <= L; j++)
|
||||
if (v[j])
|
||||
v[j] = gf_mul_tab(v[j], ajpow[j], tab);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/* Syndromes S_j = R(alpha^j) * alpha^(-j*r), j = 1..2t, from the
|
||||
* received word. Returns 0 with S filled, 1 if the remainder is
|
||||
* zero (no errors), -1 on bad input. */
|
||||
static int compute_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, bch_ctx_t *ctx,
|
||||
const gf_tables_t *tab, uint32_t *S)
|
||||
{
|
||||
int r = p->r, m = p->m, t = p->t;
|
||||
uint32_t P = bch_prim_poly[m];
|
||||
uint32_t N = (1u << m) - 1;
|
||||
int nb = (r + 7) / 8;
|
||||
size_t stored = bch_block_stored_len(data_len, p);
|
||||
if (in_len != stored)
|
||||
return -1;
|
||||
uint8_t *rem = malloc(nb);
|
||||
if (!rem)
|
||||
return -1;
|
||||
rem_of_codeword(in, data_len, in + data_len, ctx, rem);
|
||||
if (rem_is_zero(rem, nb)) {
|
||||
free(rem);
|
||||
return 1;
|
||||
}
|
||||
for (int j = 1; j <= 2 * t; j++) {
|
||||
uint32_t aj = tab->exp[j % N];
|
||||
uint32_t v = rem_eval(rem, r, aj, P, m);
|
||||
uint32_t e = (uint32_t)(((uint64_t)j * (uint64_t)r) % N);
|
||||
uint32_t inv = (e == 0) ? 1 : tab->exp[N - e];
|
||||
S[j - 1] = gf_mul_tab(v, inv, tab);
|
||||
}
|
||||
free(rem);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Column of the parity-check matrix for bit position pos:
|
||||
* col_j = alpha^(j*(nbits-1-pos)), j = 1..2t. Fills col[0..2t-1]. */
|
||||
static void col_at(size_t pos, size_t nbits, int t, const gf_tables_t *tab,
|
||||
uint32_t *col)
|
||||
{
|
||||
uint32_t N = tab->N;
|
||||
uint32_t K = (uint32_t)(nbits - 1 - pos);
|
||||
for (int j = 1; j <= 2 * t; j++)
|
||||
col[j - 1] = tab->exp[(uint32_t)(((uint64_t)j * K) % N)];
|
||||
}
|
||||
|
||||
/* One Chase trial: syndrome S (2t entries) for a word that differs
|
||||
* from the received word by the trial flip(s) `flips[0..nflips-1]`.
|
||||
* Run BM, the complete-splitting filter, Chien, and the
|
||||
* zero-remainder check. The corrected word is the received word
|
||||
* with BOTH the trial flips AND the Chien roots flipped -- the
|
||||
* trial flips are part of the correction, not just a syndrome
|
||||
* tweak. On success, copy the decoded data bytes to out and
|
||||
* return 1. Stats: trials, split_pass, codewords. */
|
||||
static int chase_trial(const uint32_t *S, const uint8_t *in, size_t in_len,
|
||||
size_t data_len, const bch_poly_t *p,
|
||||
const size_t *flips, int nflips,
|
||||
const gf_tables_t *tab, bch_ctx_t *ctx,
|
||||
uint8_t *out, bch_chase_stats_t *st)
|
||||
{
|
||||
int t = p->t, m = p->m;
|
||||
size_t nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
int nb = (p->r + 7) / 8;
|
||||
uint32_t lambda[33], mono[33];
|
||||
int L = berlekamp_massey_tab(S, t, m, tab, lambda);
|
||||
st->trials++;
|
||||
if (L < 0 || L > t)
|
||||
return 0;
|
||||
/* Normalize to monic for the splitting test (roots are
|
||||
* scale-invariant, so Chien may use the normalized form too). */
|
||||
{
|
||||
uint32_t inv = gf_div_tab(1, lambda[L], tab);
|
||||
for (int i = 0; i <= L; i++)
|
||||
mono[i] = gf_mul_tab(lambda[i], inv, tab);
|
||||
}
|
||||
if (!lambda_splits(mono, L, m, tab))
|
||||
return 0;
|
||||
st->split_pass++;
|
||||
{
|
||||
size_t *pos = malloc(sizeof(size_t) * (size_t)(L > 0 ? L : 1));
|
||||
uint8_t *work, *rem;
|
||||
int found, ok;
|
||||
if (!pos)
|
||||
return 0;
|
||||
found = chien_positions(mono, L, nbits, tab, pos, L);
|
||||
if (found != L) {
|
||||
free(pos);
|
||||
return 0;
|
||||
}
|
||||
work = malloc(in_len);
|
||||
if (!work) {
|
||||
free(pos);
|
||||
return 0;
|
||||
}
|
||||
memcpy(work, in, in_len);
|
||||
/* The trial flips AND the Chien roots are both part of the
|
||||
* correction: the trial flips produced the syndrome S, and
|
||||
* the Chien roots are the remaining errors in that
|
||||
* trial-flipped word. */
|
||||
for (int i = 0; i < nflips; i++)
|
||||
flip_bit_at(work, flips[i]);
|
||||
for (int i = 0; i < found; i++)
|
||||
flip_bit_at(work, pos[i]);
|
||||
free(pos);
|
||||
rem = malloc(nb);
|
||||
if (!rem) {
|
||||
free(work);
|
||||
return 0;
|
||||
}
|
||||
rem_of_codeword(work, data_len, work + data_len, ctx, rem);
|
||||
ok = rem_is_zero(rem, nb);
|
||||
free(rem);
|
||||
if (!ok) {
|
||||
free(work);
|
||||
return 0;
|
||||
}
|
||||
st->codewords++;
|
||||
memcpy(out, work, data_len);
|
||||
free(work);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Add v to pos[0..n-1] if not already present and room remains.
|
||||
* Returns the new count. */
|
||||
static int pos_add(size_t *pos, int n, int max_pos, size_t v)
|
||||
{
|
||||
int i;
|
||||
if (n >= max_pos)
|
||||
return n;
|
||||
for (i = 0; i < n; i++)
|
||||
if (pos[i] == v)
|
||||
return n;
|
||||
pos[n++] = v;
|
||||
return n;
|
||||
}
|
||||
|
||||
int bch_suspect_positions(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, size_t *pos, int max_pos)
|
||||
{
|
||||
size_t nbits;
|
||||
size_t *E, *D;
|
||||
int n = 0, L, Ld = -1;
|
||||
if (max_pos <= 0 || !pos || !p)
|
||||
return 0;
|
||||
nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
E = malloc(sizeof(size_t) * 33);
|
||||
D = malloc(sizeof(size_t) * 33);
|
||||
if (!E || !D) {
|
||||
free(E);
|
||||
free(D);
|
||||
return 0;
|
||||
}
|
||||
L = find_errors_in(in, in_len, data_len, p, E);
|
||||
if (L > 0) {
|
||||
uint8_t *Rp = malloc(in_len);
|
||||
if (Rp) {
|
||||
int i;
|
||||
memcpy(Rp, in, in_len);
|
||||
for (i = 0; i < L; i++)
|
||||
flip_bit_at(Rp, E[i]);
|
||||
Ld = find_errors_in(Rp, in_len, data_len, p, D);
|
||||
free(Rp);
|
||||
}
|
||||
}
|
||||
if (L > 0) {
|
||||
int i, j;
|
||||
for (i = 0; i < L; i++)
|
||||
n = pos_add(pos, n, max_pos, E[i]);
|
||||
for (j = 0; j < Ld; j++)
|
||||
n = pos_add(pos, n, max_pos, D[j]);
|
||||
for (i = 0; i < L; i++) {
|
||||
if (E[i] > 0)
|
||||
n = pos_add(pos, n, max_pos, E[i] - 1);
|
||||
if (E[i] + 1 < nbits)
|
||||
n = pos_add(pos, n, max_pos, E[i] + 1);
|
||||
}
|
||||
}
|
||||
free(E);
|
||||
free(D);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Shared Chase setup: returns 0 with *ctx_out, *tab_out, *S_out
|
||||
* (2t syndromes) filled, or -1. The caller frees ctx and S.
|
||||
* Returns 1 when there is nothing to chase (standard decode
|
||||
* already succeeds, or the word is clean). */
|
||||
static int chase_setup(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, bch_ctx_t **ctx_out,
|
||||
const gf_tables_t **tab_out, uint32_t **S_out)
|
||||
{
|
||||
int t = p->t, m = p->m;
|
||||
size_t stored = bch_block_stored_len(data_len, p);
|
||||
bch_ctx_t *ctx;
|
||||
const gf_tables_t *tab;
|
||||
uint32_t *S;
|
||||
if (in_len != stored)
|
||||
return -1;
|
||||
{
|
||||
/* Nothing to chase when the standard decoder succeeds. */
|
||||
uint8_t *dec = malloc(data_len ? data_len : 1);
|
||||
if (!dec)
|
||||
return -1;
|
||||
if (bch_decode_block(in, in_len, data_len, p, dec, NULL) == 0) {
|
||||
free(dec);
|
||||
return 1;
|
||||
}
|
||||
free(dec);
|
||||
}
|
||||
ctx = bch_ctx_new(p);
|
||||
if (!ctx)
|
||||
return -1;
|
||||
tab = gf_tables_for(m);
|
||||
if (!tab) {
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
S = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
if (!S) {
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
if (compute_syndrome(in, in_len, data_len, p, ctx, tab, S) != 0) {
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return 1; /* clean word: nothing to chase */
|
||||
}
|
||||
*ctx_out = ctx;
|
||||
*tab_out = tab;
|
||||
*S_out = S;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bch_chase1_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *cands, int max_cands,
|
||||
const size_t *suspects, int nsuspects,
|
||||
bch_chase_stats_t *stats, double deadline)
|
||||
{
|
||||
bch_chase_stats_t dummy;
|
||||
bch_ctx_t *ctx = NULL;
|
||||
const gf_tables_t *tab = NULL;
|
||||
uint32_t *S = NULL, *Sp = NULL, *col = NULL;
|
||||
uint8_t *out = NULL;
|
||||
int t, m, nc = 0, rc;
|
||||
size_t nbits;
|
||||
if (!stats)
|
||||
stats = &dummy;
|
||||
memset(stats, 0, sizeof *stats);
|
||||
if (!in || !p || !cands)
|
||||
return -1;
|
||||
if (max_cands <= 0)
|
||||
return 0;
|
||||
if (max_cands > BCH_CHASE_MAX_CANDS)
|
||||
max_cands = BCH_CHASE_MAX_CANDS;
|
||||
t = p->t;
|
||||
m = p->m;
|
||||
nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
rc = chase_setup(in, in_len, data_len, p, &ctx, &tab, &S);
|
||||
if (rc != 0)
|
||||
return rc < 0 ? -1 : 0;
|
||||
Sp = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
col = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
out = malloc(data_len ? data_len : 1);
|
||||
if (!Sp || !col || !out) {
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
/* Phase A: suspect positions first (direct columns). */
|
||||
{
|
||||
int si;
|
||||
for (si = 0; si < nsuspects && nc < max_cands; si++) {
|
||||
size_t s = suspects ? suspects[si] : 0;
|
||||
int j;
|
||||
if (!suspects || s >= nbits)
|
||||
continue;
|
||||
col_at(s, nbits, t, tab, col);
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
Sp[j] = S[j] ^ col[j];
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, &s, 1, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
if (deadline >= 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Phase B: exhaustive ascending scan with incremental columns.
|
||||
* cur[j] = alpha^(j*K) for the current position (K = n-1-p);
|
||||
* each step multiplies by alpha^(-j). */
|
||||
{
|
||||
uint32_t *cur = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t *step = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t N;
|
||||
size_t pp;
|
||||
int j;
|
||||
if (!cur || !step) {
|
||||
free(cur);
|
||||
free(step);
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
N = tab->N;
|
||||
for (j = 1; j <= 2 * t; j++) {
|
||||
cur[j - 1] = tab->exp[(uint32_t)(((uint64_t)j * (nbits - 1)) % N)];
|
||||
step[j - 1] = tab->exp[(N - (uint32_t)j) % N]; /* alpha^-j */
|
||||
}
|
||||
for (pp = 0; pp < nbits && nc < max_cands; pp++) {
|
||||
int is_suspect = 0;
|
||||
int si;
|
||||
for (si = 0; si < nsuspects; si++)
|
||||
if (suspects && suspects[si] == pp) {
|
||||
is_suspect = 1;
|
||||
break;
|
||||
}
|
||||
if (!is_suspect) {
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
Sp[j] = S[j] ^ cur[j];
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, &pp, 1, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
cur[j] = gf_mul_tab(cur[j], step[j], tab);
|
||||
if (deadline >= 0 && (pp & 255) == 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
free(cur);
|
||||
free(step);
|
||||
}
|
||||
done:
|
||||
stats->candidates = nc;
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
(void)m;
|
||||
return nc;
|
||||
}
|
||||
|
||||
int bch_chase2_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *cands, int max_cands,
|
||||
const size_t *suspects, int nsuspects,
|
||||
bch_chase_stats_t *stats, double deadline)
|
||||
{
|
||||
bch_chase_stats_t dummy;
|
||||
bch_ctx_t *ctx = NULL;
|
||||
const gf_tables_t *tab = NULL;
|
||||
uint32_t *S = NULL, *Sp = NULL, *col = NULL, *col2 = NULL;
|
||||
uint8_t *out = NULL;
|
||||
int t, m, nc = 0, rc;
|
||||
size_t nbits;
|
||||
if (!stats)
|
||||
stats = &dummy;
|
||||
memset(stats, 0, sizeof *stats);
|
||||
if (!in || !p || !cands)
|
||||
return -1;
|
||||
if (max_cands <= 0)
|
||||
return 0;
|
||||
if (max_cands > BCH_CHASE_MAX_CANDS)
|
||||
max_cands = BCH_CHASE_MAX_CANDS;
|
||||
/* No early return when suspects are empty: phase B builds its
|
||||
* first-element list from the suspects plus a positional prefix,
|
||||
* so it runs even with an empty suspect set. */
|
||||
t = p->t;
|
||||
m = p->m;
|
||||
nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
rc = chase_setup(in, in_len, data_len, p, &ctx, &tab, &S);
|
||||
if (rc != 0)
|
||||
return rc < 0 ? -1 : 0;
|
||||
Sp = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
col = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
col2 = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
out = malloc(data_len ? data_len : 1);
|
||||
if (!Sp || !col || !col2 || !out) {
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(col2);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
/* Phase A: pairs within the suspect set. */
|
||||
{
|
||||
int i, j, k;
|
||||
for (i = 0; i < nsuspects && nc < max_cands; i++) {
|
||||
size_t si = suspects[i];
|
||||
if (si >= nbits)
|
||||
continue;
|
||||
col_at(si, nbits, t, tab, col);
|
||||
for (j = i + 1; j < nsuspects && nc < max_cands; j++) {
|
||||
size_t sj = suspects[j];
|
||||
if (sj >= nbits)
|
||||
continue;
|
||||
col_at(sj, nbits, t, tab, col2);
|
||||
for (k = 0; k < 2 * t; k++)
|
||||
Sp[k] = S[k] ^ col[k] ^ col2[k];
|
||||
{
|
||||
size_t fl[2];
|
||||
fl[0] = si;
|
||||
fl[1] = sj;
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, fl, 2, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
if (deadline >= 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Phase B: (first-element, any-position) pairs. The first
|
||||
* element ranges over a bounded list: the suspect set first,
|
||||
* then ascending bit positions, capped at
|
||||
* BCH_CHASE2_FIRST_MAX entries in total. For a fixed first
|
||||
* element s, base = S ^ col(s); q scans ascending with
|
||||
* incremental col(q). A pair {a,b} with both ends in the
|
||||
* first list is tried once, at the smaller outer element
|
||||
* (skip q in the list with q < s); pairs with one end
|
||||
* outside the list are tried when the outer element is the
|
||||
* in-list end. Trial count is bounded by
|
||||
* BCH_CHASE2_FIRST_MAX * nbits, and the deadline caps the
|
||||
* wall time. Why the positional prefix: the failed decode's
|
||||
* Chien roots provably do not overlap the true errors (the
|
||||
* two same-syndrome patterns differ by a codeword of weight
|
||||
* >= 2t+1, forcing zero overlap when the failed decode
|
||||
* returns a full root set), so for random error patterns a
|
||||
* suspect is no more likely than any other position to be a
|
||||
* true error. The recovery probability therefore scales
|
||||
* with the size of the first-element list: roughly
|
||||
* 1 - (1 - (t+2)/nbits)^F for F first elements, and the
|
||||
* list is what buys the rate. */
|
||||
{
|
||||
uint32_t *base = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t *cur = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t *step = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t N;
|
||||
size_t first[BCH_CHASE2_FIRST_MAX];
|
||||
int nfirst = 0, si, j;
|
||||
size_t P = 0; /* prefix length: positions < P are in the
|
||||
* first list unless they are suspects,
|
||||
* and every suspect is in the list */
|
||||
if (!base || !cur || !step) {
|
||||
free(base);
|
||||
free(cur);
|
||||
free(step);
|
||||
goto done;
|
||||
}
|
||||
for (si = 0; si < nsuspects && nfirst < BCH_CHASE2_FIRST_MAX; si++)
|
||||
if (suspects[si] < nbits)
|
||||
first[nfirst++] = suspects[si];
|
||||
{
|
||||
size_t pp;
|
||||
for (pp = 0; pp < nbits && nfirst < BCH_CHASE2_FIRST_MAX; pp++) {
|
||||
int dup = 0, sj;
|
||||
for (sj = 0; sj < nfirst; sj++)
|
||||
if (first[sj] == pp) {
|
||||
dup = 1;
|
||||
break;
|
||||
}
|
||||
if (!dup)
|
||||
first[nfirst++] = pp;
|
||||
P = pp + 1;
|
||||
}
|
||||
}
|
||||
N = tab->N;
|
||||
for (j = 1; j <= 2 * t; j++)
|
||||
step[j - 1] = tab->exp[(N - (uint32_t)j) % N]; /* alpha^-j */
|
||||
for (si = 0; si < nfirst && nc < max_cands; si++) {
|
||||
size_t s = first[si];
|
||||
size_t q;
|
||||
col_at(s, nbits, t, tab, col);
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
base[j] = S[j] ^ col[j];
|
||||
for (j = 1; j <= 2 * t; j++)
|
||||
cur[j - 1] = tab->exp[(uint32_t)(((uint64_t)j * (nbits - 1)) % N)];
|
||||
for (q = 0; q < nbits && nc < max_cands; q++) {
|
||||
int in_first = (q < P);
|
||||
int sj;
|
||||
if (!in_first)
|
||||
for (sj = 0; sj < nsuspects; sj++)
|
||||
if (suspects[sj] == q) {
|
||||
in_first = 1;
|
||||
break;
|
||||
}
|
||||
if (q != s && !(in_first && q < s)) {
|
||||
size_t fl[2];
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
Sp[j] = base[j] ^ cur[j];
|
||||
fl[0] = s;
|
||||
fl[1] = q;
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, fl, 2, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
cur[j] = gf_mul_tab(cur[j], step[j], tab);
|
||||
if (deadline >= 0 && (q & 255) == 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (stats->partial)
|
||||
break;
|
||||
}
|
||||
free(base);
|
||||
free(cur);
|
||||
free(step);
|
||||
}
|
||||
done:
|
||||
stats->candidates = nc;
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(col2);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
(void)m;
|
||||
return nc;
|
||||
}
|
||||
@@ -106,107 +106,4 @@ int bch_decode_candidates(const uint8_t *in, size_t len, size_t orig_len,
|
||||
int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *rem_out);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Deep repair: Chase / list decoding past t (lzply_deep_repair). */
|
||||
/* */
|
||||
/* The standard decoder corrects up to t bit errors per block. Past */
|
||||
/* t it fails or miscorrects. The Chase levels below recover data */
|
||||
/* past t by trial flips, verified against an external oracle (the */
|
||||
/* caller CRC16/SHA-256-checks every candidate; nothing here is ever */
|
||||
/* returned as "the" answer). */
|
||||
/* */
|
||||
/* Method. Flipping one bit at position p changes the syndrome by */
|
||||
/* the column col(p): S_j ^= alpha^(j*(n-1-p)), j = 1..2t. A trial */
|
||||
/* flip is GOOD (it hit a true error, leaving t errors) iff the */
|
||||
/* Berlekamp-Massey locator for the flipped syndrome splits */
|
||||
/* completely over GF(2^m) with all roots at in-range positions and */
|
||||
/* the corrected word has zero remainder. The splitting test is a */
|
||||
/* gcd with x^(2^m) - x (m repeated squarings mod the locator): it */
|
||||
/* costs O(m*t^2) field operations per trial, versus O(n*t) for a */
|
||||
/* full Chien search, so it filters the trials cheaply and Chien */
|
||||
/* runs only for the rare survivors (a random degree-L locator */
|
||||
/* splits with probability ~1/L!). */
|
||||
/* */
|
||||
/* Bounds (all documented, all enforced): */
|
||||
/* chase1: at most nbits trials (one per codeword bit position), */
|
||||
/* suspects first, then an exhaustive ascending scan. */
|
||||
/* chase2: pairs (s, q) with s from a bounded first-element list */
|
||||
/* (the suspect set, then ascending bit positions, at most */
|
||||
/* BCH_CHASE2_FIRST_MAX entries) and q over all positions, plus */
|
||||
/* pairs within the suspect set: at most */
|
||||
/* BCH_CHASE2_FIRST_MAX*nbits + 496 trials. */
|
||||
/* candidates: at most BCH_CHASE_MAX_CANDS distinct decoded blocks */
|
||||
/* per call. A wall-clock deadline (monotonic seconds, < 0 = */
|
||||
/* none) stops a scan early; stats.partial says so, and */
|
||||
/* stats.trials says how far the scan got. */
|
||||
/* */
|
||||
/* "Least-reliable bits": with hard-decision input there is no */
|
||||
/* channel reliability, so suspicion comes from the decoder itself: */
|
||||
/* the Chien roots of the failed decode, the residual-BM difference */
|
||||
/* set, and their neighbours. Those positions are tried first */
|
||||
/* (chase1 phase A). For chase2 they head the first-element list, */
|
||||
/* followed by a positional prefix, because the failed decode's */
|
||||
/* roots provably do NOT overlap the true errors for random */
|
||||
/* patterns: the failed decode's root set and the true error set */
|
||||
/* have the same syndrome, so they differ by a codeword of weight */
|
||||
/* >= 2t+1, which forces zero overlap when the failed decode */
|
||||
/* returns a full root set. A suspect is therefore no more likely */
|
||||
/* than any other position to be a true error, and chase2's */
|
||||
/* recovery rate scales with the size of the first-element list: */
|
||||
/* roughly 1 - (1 - (t+2)/nbits)^F for F first elements on a */
|
||||
/* weight-(t+2) pattern. The list is what buys the rate. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* Maximum distinct candidate blocks returned per chase call. */
|
||||
#define BCH_CHASE_MAX_CANDS 64
|
||||
/* Maximum suspect positions considered by chase2. */
|
||||
#define BCH_CHASE_MAX_SUSPECTS 32
|
||||
/* Maximum first elements in a chase2 pair scan (suspects, then a
|
||||
* positional prefix). Trial count is bounded by this times nbits. */
|
||||
#define BCH_CHASE2_FIRST_MAX 128
|
||||
|
||||
typedef struct {
|
||||
long trials; /* BM runs (one per trial flip / flip pair) */
|
||||
long split_pass; /* trials whose locator splits over GF(2^m) */
|
||||
long codewords; /* trials yielding a valid (zero-remainder) codeword */
|
||||
long candidates; /* distinct candidate blocks returned */
|
||||
int partial; /* scan stopped early (deadline hit) */
|
||||
} bch_chase_stats_t;
|
||||
|
||||
/* Monotonic seconds (CLOCK_MONOTONIC), for repair time budgets. */
|
||||
double bch_now(void);
|
||||
|
||||
/* Suspect positions for a block the standard decoder failed on:
|
||||
* Chien roots of the failed decode, residual-BM difference
|
||||
* positions, and neighbours of the roots -- in that priority order,
|
||||
* deduplicated, capped at max_pos. Returns the count (0 when the
|
||||
* failed decode yields no usable positions). Does not modify `in`.
|
||||
* `pos` must hold max_pos entries. */
|
||||
int bch_suspect_positions(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, size_t *pos, int max_pos);
|
||||
|
||||
/* Chase-1 for one block: single-bit trial flips. Tries the suspect
|
||||
* positions first (in order), then every other bit position in
|
||||
* ascending order. Returns the number of distinct candidate decoded
|
||||
* blocks in `cands` (each data_len bytes, 0..max_cands), or -1 on
|
||||
* bad input. Returns 0 when the standard decoder already succeeds
|
||||
* (nothing to chase). `suspects` may be NULL (with nsuspects 0).
|
||||
* `deadline` is an absolute bch_now() time, or < 0 for no deadline.
|
||||
* Stats are zeroed on entry (NULL is allowed). */
|
||||
int bch_chase1_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *cands, int max_cands,
|
||||
const size_t *suspects, int nsuspects,
|
||||
bch_chase_stats_t *stats, double deadline);
|
||||
|
||||
/* Chase-2 for one block: two-bit trial flips. First all pairs within
|
||||
* the suspect set, then (first-element, any-position) pairs where
|
||||
* the first element ranges over a bounded list: the suspects, then
|
||||
* ascending bit positions, capped at BCH_CHASE2_FIRST_MAX entries.
|
||||
* Same return contract as bch_chase1_block. `suspects` may be NULL
|
||||
* (with nsuspects 0); the positional prefix still runs. */
|
||||
int bch_chase2_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *cands, int max_cands,
|
||||
const size_t *suspects, int nsuspects,
|
||||
bch_chase_stats_t *stats, double deadline);
|
||||
|
||||
#endif /* LZPLY_BCH_H */
|
||||
-205
@@ -398,211 +398,6 @@ int main(int argc, char **argv)
|
||||
CHECK(silent == 0, "pass2: %d silent wrong outputs", silent);
|
||||
}
|
||||
|
||||
/* --- 8: deep repair (Chase-1 / Chase-2 past t) --- */
|
||||
{
|
||||
/* Small blocks (D=512) so the exhaustive Chase-1 scan is
|
||||
* fast. For each t, corrupt with t+1 bits (one past the
|
||||
* limit) and t+2 bits (two past). Invariants checked:
|
||||
* - standard decode fails at t+1/t+2 (control: the repair
|
||||
* levels are actually needed);
|
||||
* - Chase-1 recovers t+1 essentially always (flipping any
|
||||
* one true error leaves t errors, which BM corrects --
|
||||
* this is a theorem, not luck);
|
||||
* - Chase-1 NEVER recovers t+2 (one flip + <= t Chien
|
||||
* corrections cannot span t+2 errors -- also a theorem);
|
||||
* - Chase-2 recovers t+2 sometimes (its first-element list
|
||||
* must contain a true error; with 128 first elements the
|
||||
* rate is roughly 1 - (1 - (t+2)/nbits)^128 -- measured,
|
||||
* not assumed; the t+2 cells use 256-byte blocks so the
|
||||
* rate is high enough to assert on);
|
||||
* - every candidate a Chase call returns is a VALID
|
||||
* codeword (zero remainder) -- wrong candidates are
|
||||
* possible in principle, so the test re-decodes each
|
||||
* returned candidate and requires it to decode cleanly;
|
||||
* the caller (CRC16/SHA-256) is what rejects wrong ones.
|
||||
* - a deadline in the past stops the scan with partial=1.
|
||||
* Deterministic: fixed RNG seed (argv seed or default). */
|
||||
static const int ts[] = { 4, 8 };
|
||||
int rec1 = 0, tot1 = 0, rec2 = 0, tot2 = 0, c1bad = 0;
|
||||
int wrong_cand = 0, tot_cand = 0, ns_empty = 0;
|
||||
for (int ti = 0; ti < 2; ti++) {
|
||||
int t = ts[ti];
|
||||
const bch_poly_t *p = bch_poly_for_data(512, t);
|
||||
CHECK(p != NULL, "chase: poly for 512B t=%d", t);
|
||||
if (!p)
|
||||
continue;
|
||||
size_t D = 512;
|
||||
size_t slen = bch_block_stored_len(D, p);
|
||||
size_t nbits = (size_t)8 * D + (size_t)p->r;
|
||||
uint8_t *data = malloc(D);
|
||||
uint8_t *enc = malloc(slen);
|
||||
uint8_t *dec = malloc(D);
|
||||
uint8_t *cands = malloc((size_t)BCH_CHASE_MAX_CANDS * D);
|
||||
rand_bytes(data, D);
|
||||
CHECK(bch_encode_block(data, D, p, enc) == 0,
|
||||
"chase encode t=%d", t);
|
||||
/* t+1 errors: Chase-1 must recover, standard must fail. */
|
||||
for (int tr = 0; tr < 10; tr++) {
|
||||
uint8_t *cor = malloc(slen);
|
||||
bch_chase_stats_t cs;
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
int ns, nc, found = 0, q;
|
||||
memcpy(cor, enc, slen);
|
||||
flip_bits(cor, nbits, t + 1);
|
||||
CHECK(bch_decode_block(cor, slen, D, p, dec, NULL) != 0,
|
||||
"chase control: standard decode must fail t=%d k=%d",
|
||||
t, t + 1);
|
||||
ns = bch_suspect_positions(cor, slen, D, p, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
/* Suspects may be empty: when the failed decode's
|
||||
* locator has no in-range roots there is nothing
|
||||
* to suspect. Chase-1 does not need them (it scans
|
||||
* exhaustively) and Chase-2 falls back to its
|
||||
* positional prefix. Count it, do not fail on it. */
|
||||
if (ns == 0)
|
||||
ns_empty++;
|
||||
for (q = 0; q < ns; q++)
|
||||
CHECK(susp[q] < nbits,
|
||||
"chase: suspect %zu in range (nbits %zu)",
|
||||
susp[q], nbits);
|
||||
nc = bch_chase1_block(cor, slen, D, p, cands,
|
||||
BCH_CHASE_MAX_CANDS, susp, ns, &cs,
|
||||
-1);
|
||||
CHECK(nc >= 0 && nc <= BCH_CHASE_MAX_CANDS,
|
||||
"chase1: candidate count %d t=%d", nc, t);
|
||||
CHECK(cs.partial == 0, "chase1: no deadline, no partial");
|
||||
for (q = 0; q < nc; q++) {
|
||||
tot_cand++;
|
||||
if (memcmp(cands + (size_t)q * D, data, D) == 0)
|
||||
found = 1;
|
||||
else {
|
||||
/* A wrong candidate must still be a valid
|
||||
* codeword: re-encode it and require the
|
||||
* re-encoded form to decode cleanly. */
|
||||
uint8_t *re = malloc(slen);
|
||||
uint8_t *dd = malloc(D);
|
||||
if (bch_encode_block(cands + (size_t)q * D, D, p,
|
||||
re) == 0 &&
|
||||
bch_decode_block(re, slen, D, p, dd, NULL) == 0 &&
|
||||
memcmp(dd, cands + (size_t)q * D, D) == 0) {
|
||||
wrong_cand++;
|
||||
} else {
|
||||
CHECK(0, "chase1: candidate %d is not a valid "
|
||||
"codeword t=%d", q, t);
|
||||
}
|
||||
free(re);
|
||||
free(dd);
|
||||
}
|
||||
}
|
||||
tot1++;
|
||||
rec1 += found;
|
||||
if (!found)
|
||||
c1bad++;
|
||||
free(cor);
|
||||
free(susp);
|
||||
}
|
||||
/* t+2 errors: Chase-1 must NOT recover; Chase-2 may.
|
||||
* 256-byte blocks here: chase2's 128 first elements
|
||||
* cover a bigger fraction of a 256-byte block, so the
|
||||
* recovery rate is high enough to assert on (roughly
|
||||
* 1 - (1 - (t+2)/nbits)^128, about 46% at t=8). */
|
||||
for (int tr = 0; tr < 5; tr++) {
|
||||
const bch_poly_t *p2 = bch_poly_for_data(256, t);
|
||||
size_t D2 = 256;
|
||||
size_t slen2 = bch_block_stored_len(D2, p2);
|
||||
size_t nbits2 = (size_t)8 * D2 + (size_t)p2->r;
|
||||
uint8_t *data2 = malloc(D2);
|
||||
uint8_t *enc2 = malloc(slen2);
|
||||
uint8_t *cor = malloc(slen2);
|
||||
bch_chase_stats_t cs1, cs2;
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
int ns, nc1, nc2, found2 = 0, q;
|
||||
CHECK(p2 != NULL, "chase2: poly for 256B t=%d", t);
|
||||
rand_bytes(data2, D2);
|
||||
CHECK(bch_encode_block(data2, D2, p2, enc2) == 0,
|
||||
"chase2 encode t=%d", t);
|
||||
memcpy(cor, enc2, slen2);
|
||||
flip_bits(cor, nbits2, t + 2);
|
||||
CHECK(bch_decode_block(cor, slen2, D2, p2, NULL, NULL) != 0,
|
||||
"chase2 control: standard decode must fail t=%d",
|
||||
t);
|
||||
ns = bch_suspect_positions(cor, slen2, D2, p2, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
if (ns == 0)
|
||||
ns_empty++;
|
||||
nc1 = bch_chase1_block(cor, slen2, D2, p2, cands,
|
||||
BCH_CHASE_MAX_CANDS, susp, ns, &cs1,
|
||||
-1);
|
||||
for (q = 0; q < nc1; q++)
|
||||
CHECK(memcmp(cands + (size_t)q * D2, data2, D2) != 0,
|
||||
"chase1: must NOT recover t+2 (t=%d trial %d)",
|
||||
t, tr);
|
||||
nc2 = bch_chase2_block(cor, slen2, D2, p2, cands,
|
||||
BCH_CHASE_MAX_CANDS, susp, ns, &cs2,
|
||||
-1);
|
||||
CHECK(nc2 >= 0 && nc2 <= BCH_CHASE_MAX_CANDS,
|
||||
"chase2: candidate count %d t=%d", nc2, t);
|
||||
CHECK(cs2.partial == 0, "chase2: no deadline, no partial");
|
||||
for (q = 0; q < nc2; q++) {
|
||||
tot_cand++;
|
||||
if (memcmp(cands + (size_t)q * D2, data2, D2) == 0)
|
||||
found2 = 1;
|
||||
else
|
||||
wrong_cand++;
|
||||
}
|
||||
tot2++;
|
||||
rec2 += found2;
|
||||
free(data2);
|
||||
free(enc2);
|
||||
free(cor);
|
||||
free(susp);
|
||||
}
|
||||
free(data);
|
||||
free(enc);
|
||||
free(dec);
|
||||
free(cands);
|
||||
}
|
||||
printf("phase 8 (deep repair Chase): t+1 recovered by Chase-1 "
|
||||
"%d/%d (missed %d), t+2 recovered by Chase-2 %d/%d, "
|
||||
"wrong-but-valid candidates %d/%d, empty suspect sets "
|
||||
"%d\n",
|
||||
rec1, tot1, c1bad, rec2, tot2, wrong_cand, tot_cand,
|
||||
ns_empty);
|
||||
CHECK(rec1 >= tot1 - 1,
|
||||
"chase1: t+1 recovery %d/%d (expected >= %d)", rec1, tot1,
|
||||
tot1 - 1);
|
||||
CHECK(rec2 >= 1, "chase2: t+2 recovery %d/%d (expected >= 1)",
|
||||
rec2, tot2);
|
||||
/* Deadline: a deadline already in the past stops the scan. */
|
||||
{
|
||||
const bch_poly_t *p = bch_poly_for_data(512, 8);
|
||||
size_t D = 512;
|
||||
size_t slen = bch_block_stored_len(D, p);
|
||||
uint8_t *data = malloc(D);
|
||||
uint8_t *enc = malloc(slen);
|
||||
uint8_t *cands = malloc((size_t)BCH_CHASE_MAX_CANDS * D);
|
||||
bch_chase_stats_t cs;
|
||||
int nc;
|
||||
rand_bytes(data, D);
|
||||
CHECK(bch_encode_block(data, D, p, enc) == 0,
|
||||
"chase deadline encode");
|
||||
flip_bits(enc, (size_t)8 * D + (size_t)p->r, 9);
|
||||
nc = bch_chase1_block(enc, slen, D, p, cands,
|
||||
BCH_CHASE_MAX_CANDS, NULL, 0, &cs,
|
||||
bch_now() - 1.0);
|
||||
CHECK(cs.partial == 1,
|
||||
"chase1: past deadline must set partial (got %d, nc %d)",
|
||||
cs.partial, nc);
|
||||
CHECK(bch_now() >= 0, "bch_now returns a time");
|
||||
free(data);
|
||||
free(enc);
|
||||
free(cands);
|
||||
}
|
||||
}
|
||||
printf("phase 8 done: %d checks, %d fails\n", checks, fails);
|
||||
|
||||
/* --- 7: unknown / edge lookups --- */
|
||||
CHECK(bch_poly_by_id(0x0000) == NULL, "id 0000 should be NULL");
|
||||
CHECK(bch_poly_by_id(0x0053) == NULL, "id 0053 should be NULL");
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Benchmarks for the integrated winners vs plain lzply at b27b345.
|
||||
# Runs on hot_newyork in the integrated checkout. The lzply core is
|
||||
# untouched by the integration (binaries md5-identical to pristine
|
||||
# b27b345), so the lzply numbers below ARE the plain-b27b345 numbers.
|
||||
# Each timed measurement is best-of-3; sizes are exact.
|
||||
# Output: stdout + results file $OUT.
|
||||
set -u
|
||||
ROOT=$PWD
|
||||
W=$ROOT/testwork-bench
|
||||
OUT=$W/bench-results.txt
|
||||
mkdir -p "$W"
|
||||
: > "$OUT"
|
||||
say() { printf '%s\n' "$*" | tee -a "$OUT"; }
|
||||
# t3 <label> <cmd...>: best-of-3 wall seconds
|
||||
t3() {
|
||||
label=$1; shift
|
||||
best=""
|
||||
for i in 1 2 3; do
|
||||
s=$(date +%s.%N)
|
||||
"$@" >/dev/null 2>&1
|
||||
e=$(date +%s.%N)
|
||||
d=$(awk -v s="$s" -v e="$e" 'BEGIN{printf "%.3f", e-s}')
|
||||
if [ -z "$best" ] || [ "$(awk -v a="$d" -v b="$best" 'BEGIN{print (a<b)?1:0}')" = 1 ]; then best=$d; fi
|
||||
done
|
||||
say "$label best-of-3: ${best}s"
|
||||
echo "$best"
|
||||
}
|
||||
say "== benchmark run $(date -u +%Y-%m-%dT%H:%M:%SZ) hot_newyork $(nproc) cores load: $(uptime | sed 's/.*average: //')"
|
||||
say "== data set =="
|
||||
# mixed set: repo docs (text) + repo C sources (code) + system binaries
|
||||
mkdir -p "$W/mixed"
|
||||
# Varied content only: repetition compresses to ~nothing under lzip.
|
||||
find "$ROOT" -type f \( -name "*.md" -o -name "*.c" -o -name "*.h" -o -name "*.sh" -o -name "*.py" -o -name "*.txt" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -not -path "$ROOT/testdata/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/mixed/text.txt"
|
||||
find "$ROOT" -type f \( -name "*.c" -o -name "*.h" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/mixed/code.c"
|
||||
cp /bin/ls /bin/cat /usr/bin/lzip "$W/mixed/" 2>/dev/null
|
||||
head -c 1048576 /dev/urandom > "$W/rand1m.bin"
|
||||
ls -l "$W/mixed" | tee -a "$OUT"
|
||||
say "mixed dir bytes: $(du -sb "$W/mixed" | cut -f1); rand1m: 1048576"
|
||||
lzip -6 -c "$W/mixed/text.txt" > "$W/text.lz"
|
||||
lzip -6 -c "$W/mixed/code.c" > "$W/code.lz"
|
||||
cat "$W/text.lz" "$W/code.lz" > "$W/mixed.lz"
|
||||
say "lzip -6 blobs: text.lz $(stat -c%s "$W/text.lz"), code.lz $(stat -c%s "$W/code.lz"), mixed.lz $(stat -c%s "$W/mixed.lz")"
|
||||
|
||||
say ""
|
||||
say "== plain lzply at b27b345 (integrated binary, md5 = pristine) =="
|
||||
"$ROOT/lzply" -c -y -6 "$W/mixed" "$W/mixed.lzply" >/dev/null 2>&1
|
||||
say "lzply -c -6 mixed: $(stat -c%s "$W/mixed.lzply") bytes"
|
||||
t3 "lzply -c -6 mixed" "$ROOT/lzply" -c -y -6 "$W/mixed" "$W/mixed.lzply" > /dev/null
|
||||
mkdir -p "$W/mixed-out"
|
||||
t3 "lzply -d mixed" "$ROOT/lzply" -d -y "$W/mixed.lzply" "$W/mixed-out" > /dev/null
|
||||
"$ROOT/lzply" -c -y -6 -e 0 "$W/mixed" "$W/mixed-e0.lzply" >/dev/null 2>&1
|
||||
say "lzply -c -6 -e 0 mixed: $(stat -c%s "$W/mixed-e0.lzply") bytes (no BCH)"
|
||||
"$ROOT/lzply" -c -y -6 "$W/rand1m.bin" "$W/rand.lzply" >/dev/null 2>&1
|
||||
say "lzply -c -6 rand1m: $(stat -c%s "$W/rand.lzply") bytes (stored, level 0 expected)"
|
||||
t3 "lzply -c -6 rand1m" "$ROOT/lzply" -c -y -6 "$W/rand1m.bin" "$W/rand.lzply" > /dev/null
|
||||
t3 "lzply -d rand1m" "$ROOT/lzply" -d -y "$W/rand.lzply" "$W/rand-out" > /dev/null
|
||||
|
||||
say ""
|
||||
say "== exp bench --speed, 64 KiB windows, mixed.lz blob =="
|
||||
for c in bch-t32 bch1k-t32 intlv-d64-bch1k-t32 ldpc-r90; do
|
||||
"$ROOT/exp/bench" --codec "$c" --blob "$W/mixed.lz" --size 65536 --speed --out "$W/speed-$c.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
|
||||
done
|
||||
say "CSV (codec,corpus,win,trials,mode,param,success,rescued,rate,enc_MBps,dec_MBps,rss_kb,ovh_pct):"
|
||||
cat "$W"/speed-*.csv | tee -a "$OUT"
|
||||
|
||||
say ""
|
||||
say "== exp bench: recovery on the mixed blob (20 trials) =="
|
||||
"$ROOT/exp/bench" --codec intlv-d64-bch1k-t32 --blob "$W/mixed.lz" --size 65536 --trials 20 --burst 256,1 --out "$W/mixed-intlv-burst.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
|
||||
"$ROOT/exp/bench" --codec bch1k-t32 --blob "$W/mixed.lz" --size 65536 --trials 20 --ber 1e-3 --out "$W/mixed-bch1k-ber.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
|
||||
"$ROOT/exp/bench" --codec ldpc-r90 --blob "$W/mixed.lz" --size 65536 --trials 10 --ber 1e-3 --out "$W/mixed-ldpc-ber.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
|
||||
|
||||
say ""
|
||||
say "== dict transform vs plain lzip -6 (sizes, bytes) =="
|
||||
for f in text code; do
|
||||
if [ "$f" = text ]; then SRC="$W/mixed/text.txt"; else SRC="$W/mixed/code.c"; fi
|
||||
lzip -6 -c "$SRC" > "$W/$f.plain.lz"
|
||||
"$ROOT/experiments/dict" c "$SRC" "$W/$f.dict" && lzip -6 -k -f "$W/$f.dict"
|
||||
say "$f: plain lzip6 $(stat -c%s "$W/$f.plain.lz") vs dict+lzip6 $(stat -c%s "$W/$f.dict.lz")"
|
||||
done
|
||||
|
||||
say ""
|
||||
say "== rANS order-0 (infrastructure context) =="
|
||||
"$ROOT/experiments/rans_tool" c "$W/mixed/text.txt" "$W/text.rans"
|
||||
say "text: plain $(stat -c%s "$W/mixed/text.txt") -> rANS order-0 $(stat -c%s "$W/text.rans")"
|
||||
t3 "rans_tool c text" "$ROOT/experiments/rans_tool" c "$W/mixed/text.txt" "$W/text.rans" > /dev/null
|
||||
t3 "rans_tool d text" "$ROOT/experiments/rans_tool" d "$W/text.rans" "$W/text.rans.out" > /dev/null
|
||||
say "== done =="
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Baseline ratio / speed / memory benchmark for lzply (experiments/baseline).
|
||||
# Usage: bench.sh <lzply-binary> <corpus-dir> <work-dir>
|
||||
# Corpus dir: enwik8 + silesia files (see docs/BASELINE.md for checksums).
|
||||
# Each setting: encode once, decode once, timed with /usr/bin/time -v
|
||||
# (max RSS), sizes from stat. Clean round-trips verified bit-identical
|
||||
# with diff -r (any mismatch is reported in the roundtrip field).
|
||||
set -u
|
||||
LZPLY="$1"; CORPUS="$2"; WORK="$3"
|
||||
mkdir -p "$WORK"
|
||||
cd "$WORK" || exit 1
|
||||
|
||||
( cd "$CORPUS" && sha256sum enwik8 dickens mozilla mr nci ooffice osdb reymont samba sao webster x-ray xml > "$WORK/corpus.sha256" )
|
||||
echo "corpus total bytes: $(du -sb "$CORPUS" | cut -f1)"
|
||||
|
||||
run_one() { # run_one <label> <input-path> <lzply -c flags...>
|
||||
local label="$1" input="$2"; shift 2
|
||||
local arc="$WORK/$label.lzply" out="$WORK/$label.out"
|
||||
rm -rf "$arc" "$out"
|
||||
/usr/bin/time -v "$LZPLY" -c "$@" "$input" "$arc" > "$WORK/$label.enc.log" 2> "$WORK/$label.enc.time"
|
||||
local enc_rc=$?
|
||||
local enc_wall=$(grep "Elapsed (wall clock)" "$WORK/$label.enc.time" | awk '{print $NF}')
|
||||
local enc_rss=$(grep "Maximum resident" "$WORK/$label.enc.time" | awk '{print $NF}')
|
||||
local arc_size=$(stat -c%s "$arc" 2>/dev/null || echo 0)
|
||||
/usr/bin/time -v "$LZPLY" -d -y "$arc" "$out" > "$WORK/$label.dec.log" 2> "$WORK/$label.dec.time"
|
||||
local dec_rc=$?
|
||||
local dec_wall=$(grep "Elapsed (wall clock)" "$WORK/$label.dec.time" | awk '{print $NF}')
|
||||
local dec_rss=$(grep "Maximum resident" "$WORK/$label.dec.time" | awk '{print $NF}')
|
||||
local rt="?"
|
||||
if [ $dec_rc -eq 0 ]; then
|
||||
if diff -r -q "$input" "$out/$(basename "$input")" > /dev/null 2>&1; then rt="IDENTICAL"; else rt="MISMATCH"; fi
|
||||
else rt="DECODE-FAILED"; fi
|
||||
echo "$label enc_rc=$enc_rc enc_wall=$enc_wall enc_maxrss_kb=$enc_rss arc_bytes=$arc_size dec_rc=$dec_rc dec_wall=$dec_wall dec_maxrss_kb=$dec_rss roundtrip=$rt"
|
||||
}
|
||||
|
||||
run_one enwik8-l1 "$CORPUS/enwik8" -1 -e 4
|
||||
run_one enwik8-l6 "$CORPUS/enwik8" -6 -e 4
|
||||
run_one enwik8-l9 "$CORPUS/enwik8" -9 -e 4
|
||||
run_one corpus-l6e4 "$CORPUS" -6 -e 4
|
||||
run_one corpus-l6e0 "$CORPUS" -6 -e 0
|
||||
run_one corpus-l6e7 "$CORPUS" -6 -e 7
|
||||
run_one mozilla-l6 "$CORPUS/mozilla" -6 -e 4
|
||||
echo DONE
|
||||
@@ -1,104 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Corruption-matrix harness for lzply baseline (experiments/baseline).
|
||||
|
||||
Builds a single-entry archive of a 1 MiB text slice (default -6 -e 4),
|
||||
then for each setting runs N trials: copy the archive, corrupt ONLY the
|
||||
stored-data region (headers untouched), run `lzply -t`, and on success
|
||||
also extract + verify SHA-256 of the recovered file. Reports
|
||||
recovered / failed-loud / silent-bad counts per setting.
|
||||
|
||||
Settings:
|
||||
scattered N bits: N in {1,2,4,8,9,16,32} random distinct bit positions
|
||||
burst L bytes: L in {1,2,4,8,16} consecutive bytes replaced with
|
||||
random bytes at a random offset (up to 8*L bit errors)
|
||||
|
||||
Usage: corrupt_matrix.py <lzply> <archive> <trials> [seed]
|
||||
Archive must have exactly one file entry; data offset is parsed from
|
||||
the v4 headers (global 16 + entry 78 + path_len).
|
||||
Env: MATRIX_WORKDIR (default /tmp/lzply-matrix), MATRIX_ONLY
|
||||
(comma list of kinds to run, default "bits,burst") — used to run
|
||||
the burst settings as a second concurrent process with its own
|
||||
workdir and seed while the bits run continues.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
LZPLY, ARCHIVE, TRIALS = sys.argv[1], sys.argv[2], int(sys.argv[3])
|
||||
SEED = int(sys.argv[4]) if len(sys.argv) > 4 else 20261202
|
||||
|
||||
with open(ARCHIVE, "rb") as f:
|
||||
raw = f.read()
|
||||
assert raw[:4] == b"LZPL", "not an LZPL archive"
|
||||
assert raw[4] == 4, "not v4"
|
||||
path_len = struct.unpack_from("<H", raw, 16)[0]
|
||||
data_off = 16 + 78 + path_len
|
||||
# entry header (78 bytes from offset 16): path_len u16, level/rs_level/
|
||||
# flags/reserved u8 x4, orig_size u64 @22, stored_size u64 @30,
|
||||
# blob_size u64 @38, sha256[32] @46, mode u32, mtime u64, header_crc32 u32
|
||||
orig_size, stored_size, blob_size = struct.unpack_from("<QQQ", raw, 22)
|
||||
sha = raw[46:78].hex()
|
||||
print("archive: %s data_off=%d stored=%d blob=%d orig=%d sha256=%s..."
|
||||
% (ARCHIVE, data_off, stored_size, blob_size, orig_size, sha[:16]),
|
||||
flush=True)
|
||||
data_end = data_off + stored_size
|
||||
assert data_end <= len(raw), "stored data overruns file"
|
||||
|
||||
work = os.environ.get("MATRIX_WORKDIR", "/tmp/lzply-matrix")
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
os.makedirs(work)
|
||||
|
||||
|
||||
def trial(rng, kind, n):
|
||||
p = os.path.join(work, "t.lzply")
|
||||
buf = bytearray(raw)
|
||||
if kind == "bits":
|
||||
positions = rng.sample(range(data_off * 8, data_end * 8), n)
|
||||
for pos in positions:
|
||||
buf[pos // 8] ^= 1 << (pos % 8)
|
||||
else: # burst: n consecutive bytes -> random bytes
|
||||
start = rng.randrange(data_off, data_end - n + 1)
|
||||
for i in range(n):
|
||||
buf[start + i] = rng.randrange(256)
|
||||
with open(p, "wb") as f:
|
||||
f.write(buf)
|
||||
r = subprocess.run([LZPLY, "-t", p], capture_output=True)
|
||||
if r.returncode != 0:
|
||||
return "failed-loud"
|
||||
# -t passed: extract and verify content hash to catch silent damage
|
||||
outdir = os.path.join(work, "out")
|
||||
shutil.rmtree(outdir, ignore_errors=True)
|
||||
r2 = subprocess.run([LZPLY, "-d", "-y", p, outdir],
|
||||
capture_output=True)
|
||||
if r2.returncode != 0:
|
||||
return "failed-loud"
|
||||
got = None
|
||||
for root, _, files in os.walk(outdir):
|
||||
for fn in files:
|
||||
with open(os.path.join(root, fn), "rb") as f:
|
||||
got = hashlib.sha256(f.read()).hexdigest()
|
||||
return "recovered" if got == sha else "SILENT-BAD"
|
||||
|
||||
|
||||
rng = random.Random(SEED)
|
||||
results = {}
|
||||
only = os.environ.get("MATRIX_ONLY", "bits,burst").split(",")
|
||||
for kind, sizes in (("bits", [1, 2, 4, 8, 9, 16, 32]),
|
||||
("burst", [1, 2, 4, 8, 16])):
|
||||
if kind not in only:
|
||||
continue
|
||||
for n in sizes:
|
||||
counts = {"recovered": 0, "failed-loud": 0, "SILENT-BAD": 0}
|
||||
for _ in range(TRIALS):
|
||||
counts[trial(rng, kind, n)] += 1
|
||||
results[(kind, n)] = counts
|
||||
print("%-5s n=%-3d: recovered %3d/%d failed-loud %3d silent-bad %d"
|
||||
% (kind, n, counts["recovered"], TRIALS,
|
||||
counts["failed-loud"], counts["SILENT-BAD"]), flush=True)
|
||||
bad = sum(c["SILENT-BAD"] for c in results.values())
|
||||
print("TOTAL silent-bad: %d (must be 0)" % bad)
|
||||
sys.exit(1 if bad else 0)
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
/* crc16_test.c - unit test for crc16_of (CRC-16/CCITT-FALSE).
|
||||
*
|
||||
* Checks the standard test vectors (empty -> 0xFFFF,
|
||||
* "123456789" -> 0x29B1, "A" -> 0xB915), single-bit sensitivity
|
||||
* (flipping any one bit of a buffer changes the CRC), and a
|
||||
* cross-check against an independent bit-by-bit reference
|
||||
* implementation on random buffers.
|
||||
*
|
||||
* Usage: ./crc16_test [seed]
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "lzply_lib.h"
|
||||
|
||||
static int fails = 0;
|
||||
static int checks = 0;
|
||||
#define CHECK(cond, ...) do { \
|
||||
checks++; \
|
||||
if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } \
|
||||
} while (0)
|
||||
|
||||
static uint64_t rng_state = 0xabcdef123456789ULL;
|
||||
static uint64_t xr(void)
|
||||
{
|
||||
rng_state ^= rng_state << 13;
|
||||
rng_state ^= rng_state >> 7;
|
||||
rng_state ^= rng_state << 17;
|
||||
return rng_state;
|
||||
}
|
||||
|
||||
/* Independent reference: bit-by-bit CRC-16/CCITT-FALSE. */
|
||||
static uint16_t crc16_ref(const uint8_t *p, size_t n)
|
||||
{
|
||||
uint16_t c = 0xFFFFu;
|
||||
size_t i;
|
||||
int b;
|
||||
for (i = 0; i < n; i++) {
|
||||
c ^= (uint16_t)((uint16_t)p[i] << 8);
|
||||
for (b = 0; b < 8; b++)
|
||||
c = (c & 0x8000u) ? (uint16_t)((c << 1) ^ 0x1021u)
|
||||
: (uint16_t)(c << 1);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc > 1)
|
||||
rng_state = strtoull(argv[1], NULL, 0) ^ 0x9e3779b97f4a7c15ULL;
|
||||
|
||||
/* Standard vectors. */
|
||||
CHECK(crc16_of(NULL, 0) == 0xFFFF, "empty -> 0xFFFF (got %04x)",
|
||||
(unsigned)crc16_of(NULL, 0));
|
||||
CHECK(crc16_of((const uint8_t *)"123456789", 9) == 0x29B1,
|
||||
"\"123456789\" -> 0x29B1 (got %04x)",
|
||||
(unsigned)crc16_of((const uint8_t *)"123456789", 9));
|
||||
CHECK(crc16_of((const uint8_t *)"A", 1) == 0xB915,
|
||||
"\"A\" -> 0xB915 (got %04x)",
|
||||
(unsigned)crc16_of((const uint8_t *)"A", 1));
|
||||
|
||||
/* Cross-check against the bit-by-bit reference on random
|
||||
* buffers of many lengths (including 0, 1, and odd sizes). */
|
||||
{
|
||||
static const size_t lens[] = { 0, 1, 2, 3, 7, 8, 15, 16, 31, 64,
|
||||
100, 257, 1000, 4096 };
|
||||
size_t li;
|
||||
for (li = 0; li < sizeof(lens) / sizeof(lens[0]); li++) {
|
||||
size_t n = lens[li];
|
||||
uint8_t *buf = malloc(n ? n : 1);
|
||||
size_t i;
|
||||
for (i = 0; i < n; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
CHECK(crc16_of(buf, n) == crc16_ref(buf, n),
|
||||
"ref mismatch len %zu: table %04x ref %04x",
|
||||
n, (unsigned)crc16_of(buf, n),
|
||||
(unsigned)crc16_ref(buf, n));
|
||||
free(buf);
|
||||
}
|
||||
}
|
||||
|
||||
/* Single-bit sensitivity: flipping any one bit of a buffer
|
||||
* must change the CRC (a CRC that ignores a bit is broken). */
|
||||
{
|
||||
uint8_t buf[64];
|
||||
size_t i;
|
||||
int b;
|
||||
for (i = 0; i < sizeof buf; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
for (i = 0; i < sizeof buf; i++) {
|
||||
for (b = 0; b < 8; b++) {
|
||||
uint16_t before = crc16_of(buf, sizeof buf);
|
||||
uint16_t after;
|
||||
buf[i] ^= (uint8_t)(1u << b);
|
||||
after = crc16_of(buf, sizeof buf);
|
||||
buf[i] ^= (uint8_t)(1u << b);
|
||||
CHECK(before != after,
|
||||
"bit flip at byte %zu bit %d did not change CRC",
|
||||
i, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Determinism: same input, same output, twice. */
|
||||
{
|
||||
uint8_t buf[128];
|
||||
size_t i;
|
||||
for (i = 0; i < sizeof buf; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
CHECK(crc16_of(buf, sizeof buf) == crc16_of(buf, sizeof buf),
|
||||
"determinism");
|
||||
}
|
||||
|
||||
printf("TOTAL: %d checks, %d fails\n", checks, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
-658
@@ -1,658 +0,0 @@
|
||||
/* deep_repair.c - escalating repair past the BCH limit t.
|
||||
*
|
||||
* The ladder (see deep_repair.h and docs/deep-repair.md):
|
||||
* L0: standard decode to t (BCH pass 1, RS first for LZRS).
|
||||
* L1: pass-2 candidates + Chase-1 single-bit flips.
|
||||
* L2: Chase-2 two-bit flips.
|
||||
* L3: bounded list decoding across blocks (two failing blocks
|
||||
* varied at once, from the pooled per-block candidates).
|
||||
* Every candidate blob is CRC16-checked before decompress + SHA-256.
|
||||
* Nothing is ever returned unless it passes both oracles.
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include "deep_repair.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "lzrs_lib.h"
|
||||
#include "rs.h"
|
||||
#include "sha256.h"
|
||||
|
||||
/* Decompress a blob and verify its SHA-256. Returns a malloc'd raw
|
||||
* buffer (caller frees) or NULL on failure. Level 0 means stored
|
||||
* uncompressed (the blob is the raw bytes). */
|
||||
static uint8_t *blob_to_raw(const uint8_t *blob, size_t blob_len, int level,
|
||||
const uint8_t want_sha[32], size_t *out_len)
|
||||
{
|
||||
uint8_t *out = NULL;
|
||||
size_t outl = 0;
|
||||
uint8_t sha[32];
|
||||
if (level == 0) {
|
||||
out = xmalloc(blob_len ? blob_len : 1);
|
||||
memcpy(out, blob, blob_len);
|
||||
outl = blob_len;
|
||||
} else if (lz_decompress_mem(blob, blob_len, &out, &outl) != 0) {
|
||||
return NULL;
|
||||
}
|
||||
lzply_sha256(out, outl, sha);
|
||||
if (memcmp(sha, want_sha, 32) != 0) {
|
||||
free(out);
|
||||
return NULL;
|
||||
}
|
||||
*out_len = outl;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Count differing bits between two buffers of n bytes. */
|
||||
static long count_bit_diffs(const uint8_t *a, const uint8_t *b, size_t n)
|
||||
{
|
||||
static const uint8_t pop[256] = {
|
||||
0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
|
||||
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
||||
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
||||
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
||||
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
||||
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
||||
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
||||
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
|
||||
};
|
||||
long d = 0;
|
||||
size_t i;
|
||||
for (i = 0; i < n; i++)
|
||||
d += pop[a[i] ^ b[i]];
|
||||
return d;
|
||||
}
|
||||
|
||||
/* One candidate blob: CRC-check it (cheap oracle), then decompress
|
||||
* + SHA-256 (final oracle). Returns 1 on success with *raw_out /
|
||||
* *raw_len_out filled, 0 on failure (stats updated). */
|
||||
static int try_blob(const uint8_t *blob, size_t blob_len, int level,
|
||||
const uint8_t want_sha[32], uint16_t want_crc16,
|
||||
deep_stats_t *st, uint8_t **raw_out, size_t *raw_len_out)
|
||||
{
|
||||
uint16_t got = crc16_of(blob, blob_len);
|
||||
uint8_t *raw;
|
||||
size_t raw_len = 0;
|
||||
st->cands_tried++;
|
||||
if (got != want_crc16) {
|
||||
st->crc_rejects++;
|
||||
return 0;
|
||||
}
|
||||
raw = blob_to_raw(blob, blob_len, level, want_sha, &raw_len);
|
||||
if (!raw) {
|
||||
st->sha_rejects++;
|
||||
return 0;
|
||||
}
|
||||
*raw_out = raw;
|
||||
*raw_len_out = raw_len;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Per-block candidate pool (decoded block bytes). */
|
||||
typedef struct {
|
||||
uint8_t *cands; /* n * dlen bytes */
|
||||
int n;
|
||||
size_t dlen;
|
||||
} block_pool_t;
|
||||
|
||||
/* Add a candidate block to the pool (deduped, capped). Returns 1 if
|
||||
* added, 0 if already present / pool full / pool-byte cap hit.
|
||||
* *pool_bytes tracks retained memory against DEEP_MAX_POOL_BYTES. */
|
||||
static int pool_add(block_pool_t *pool, size_t dlen, const uint8_t *cand,
|
||||
size_t *pool_bytes)
|
||||
{
|
||||
int i;
|
||||
if (pool->n >= 2 * DEEP_MAX_BLOCK_CANDS)
|
||||
return 0;
|
||||
if (*pool_bytes + dlen > DEEP_MAX_POOL_BYTES)
|
||||
return 0;
|
||||
for (i = 0; i < pool->n; i++)
|
||||
if (memcmp(pool->cands + (size_t)i * dlen, cand, dlen) == 0)
|
||||
return 0;
|
||||
{
|
||||
uint8_t *nc = realloc(pool->cands,
|
||||
(size_t)(pool->n + 1) * (dlen ? dlen : 1));
|
||||
if (!nc)
|
||||
return 0;
|
||||
pool->cands = nc;
|
||||
memcpy(pool->cands + (size_t)pool->n * dlen, cand, dlen);
|
||||
pool->n++;
|
||||
pool->dlen = dlen;
|
||||
*pool_bytes += dlen;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void pool_free(block_pool_t *pool, size_t *pool_bytes)
|
||||
{
|
||||
if (pool->cands) {
|
||||
*pool_bytes -= (size_t)pool->n * pool->dlen;
|
||||
free(pool->cands);
|
||||
pool->cands = NULL;
|
||||
}
|
||||
pool->n = 0;
|
||||
pool->dlen = 0;
|
||||
}
|
||||
|
||||
int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id, int rs_level,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint16_t want_crc16, int max_level, double budget_sec,
|
||||
uint8_t **raw, size_t *raw_len, deep_stats_t *stats)
|
||||
{
|
||||
deep_stats_t dummy;
|
||||
double start, deadline;
|
||||
const uint8_t *bch_stored = NULL; /* RS-decoded BCH bytes (owned below) */
|
||||
uint8_t *bch_owned = NULL;
|
||||
size_t bch_len = 0;
|
||||
int corr_rs = 0;
|
||||
int rc = -1;
|
||||
if (!stats)
|
||||
stats = &dummy;
|
||||
memset(stats, 0, sizeof *stats);
|
||||
stats->level_landed = -1;
|
||||
stats->bch_corrected = -1;
|
||||
strcpy(stats->fail_stage, "sha");
|
||||
if (!stored || !want_sha || !raw || !raw_len)
|
||||
return -1;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (max_level < 0)
|
||||
max_level = 0;
|
||||
if (max_level > DEEP_MAX_LEVEL)
|
||||
max_level = DEEP_MAX_LEVEL;
|
||||
if (budget_sec <= 0)
|
||||
budget_sec = DEEP_DEFAULT_BUDGET_SEC;
|
||||
if (rs_level < 0 || rs_level > 4)
|
||||
return -1;
|
||||
start = bch_now();
|
||||
deadline = start + budget_sec;
|
||||
|
||||
/* --- RS layer (LZRS only): strip it first. --- */
|
||||
if (rs_level > 0) {
|
||||
int parity = rs_parity_for_level(rs_level);
|
||||
const bch_poly_t *poly = NULL;
|
||||
if (parity < 0)
|
||||
return -1;
|
||||
if (is_bch) {
|
||||
poly = bch_poly_by_id(poly_id);
|
||||
if (!poly)
|
||||
return -1;
|
||||
bch_len = bch_encoded_len(blob_size, poly);
|
||||
} else {
|
||||
bch_len = blob_size;
|
||||
}
|
||||
if (stored_len != rs_encoded_len(bch_len, parity)) {
|
||||
strcpy(stats->fail_stage, "len");
|
||||
return -1;
|
||||
}
|
||||
bch_owned = xmalloc(bch_len ? bch_len : 1);
|
||||
if (rs_decode(stored, stored_len, bch_len, parity,
|
||||
bch_owned, &corr_rs) != 0) {
|
||||
free(bch_owned);
|
||||
strcpy(stats->fail_stage, "rs");
|
||||
stats->t_total = bch_now() - start;
|
||||
return -1;
|
||||
}
|
||||
stats->rs_corrected = corr_rs;
|
||||
bch_stored = bch_owned;
|
||||
} else {
|
||||
if (is_bch) {
|
||||
const bch_poly_t *poly = bch_poly_by_id(poly_id);
|
||||
if (!poly)
|
||||
return -1;
|
||||
bch_len = bch_encoded_len(blob_size, poly);
|
||||
if (stored_len != bch_len) {
|
||||
strcpy(stats->fail_stage, "len");
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
bch_len = blob_size;
|
||||
if (stored_len != blob_size) {
|
||||
strcpy(stats->fail_stage, "len");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
bch_stored = stored;
|
||||
}
|
||||
|
||||
/* --- No BCH layer: CRC + SHA only, nothing to repair. --- */
|
||||
if (!is_bch) {
|
||||
double t0 = bch_now();
|
||||
uint16_t got = crc16_of(bch_stored, blob_size);
|
||||
if (got != want_crc16) {
|
||||
stats->cands_tried++;
|
||||
stats->crc_rejects++;
|
||||
strcpy(stats->fail_stage, "crc");
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
free(bch_owned);
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
stats->cands_tried++;
|
||||
out = blob_to_raw(bch_stored, blob_size, level, want_sha,
|
||||
&out_len);
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
if (!out) {
|
||||
stats->sha_rejects++;
|
||||
strcpy(stats->fail_stage, "sha");
|
||||
stats->t_total = bch_now() - start;
|
||||
free(bch_owned);
|
||||
return -1;
|
||||
}
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 0;
|
||||
stats->bch_corrected = 0;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_total = bch_now() - start;
|
||||
free(bch_owned);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- BCH layer: split into blocks, pass 1 each. --- */
|
||||
{
|
||||
const bch_poly_t *poly = bch_poly_by_id(poly_id);
|
||||
size_t maxd = bch_max_data(poly);
|
||||
size_t nblocks = blob_size == 0 ? 1
|
||||
: (blob_size + maxd - 1) / maxd;
|
||||
size_t *boff = malloc(nblocks * sizeof(size_t));
|
||||
size_t *bdlen = malloc(nblocks * sizeof(size_t));
|
||||
size_t *bslen = malloc(nblocks * sizeof(size_t));
|
||||
uint8_t *ok = malloc(nblocks);
|
||||
uint8_t *base = xmalloc(blob_size ? blob_size : 1);
|
||||
uint8_t *won = xmalloc(blob_size ? blob_size : 1);
|
||||
block_pool_t *pools = calloc(nblocks, sizeof(block_pool_t));
|
||||
size_t pool_bytes = 0;
|
||||
size_t *vary = malloc(nblocks * sizeof(size_t));
|
||||
long nfail = 0, nfail_idx = 0;
|
||||
int retain_pools = 0;
|
||||
double t0;
|
||||
int corr_total = 0;
|
||||
size_t i, off = 0, roff = 0;
|
||||
if (!boff || !bdlen || !bslen || !ok || !pools || !vary) {
|
||||
free(boff); free(bdlen); free(bslen); free(ok);
|
||||
free(base); free(won); free(pools); free(vary);
|
||||
free(bch_owned);
|
||||
return -1;
|
||||
}
|
||||
stats->blocks_total = (long)nblocks;
|
||||
for (i = 0; i < nblocks; i++) {
|
||||
size_t chunk = blob_size - off;
|
||||
size_t slen;
|
||||
int c1 = 0;
|
||||
if (chunk > maxd)
|
||||
chunk = maxd;
|
||||
slen = bch_block_stored_len(chunk, poly);
|
||||
boff[i] = off;
|
||||
bdlen[i] = chunk;
|
||||
bslen[i] = slen;
|
||||
ok[i] = (roff + slen <= bch_len &&
|
||||
bch_decode_block(bch_stored + roff, slen, chunk, poly,
|
||||
base + off, &c1) == 0);
|
||||
if (!ok[i])
|
||||
nfail++;
|
||||
corr_total += c1;
|
||||
roff += slen;
|
||||
off += chunk;
|
||||
}
|
||||
stats->blocks_failed = nfail;
|
||||
/* Vary set: failing blocks; when none failed (miscorrection),
|
||||
* every block in turn. Pools are retained only when some
|
||||
* block failed (the multi-block L3 case). */
|
||||
if (nfail > 0) {
|
||||
retain_pools = 1;
|
||||
for (i = 0; i < nblocks; i++)
|
||||
if (!ok[i])
|
||||
vary[nfail_idx++] = i;
|
||||
} else {
|
||||
for (i = 0; i < nblocks; i++)
|
||||
vary[nfail_idx++] = i;
|
||||
}
|
||||
|
||||
/* --- L0: the pass-1 blob. --- */
|
||||
t0 = bch_now();
|
||||
if (nfail == 0) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
if (try_blob(base, blob_size, level, want_sha, want_crc16,
|
||||
stats, &out, &out_len)) {
|
||||
memcpy(won, base, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 0;
|
||||
stats->bch_corrected = corr_total;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
goto bch_done;
|
||||
}
|
||||
}
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
if (max_level < 1)
|
||||
goto bch_fail;
|
||||
|
||||
/* --- L1: pass-2 candidates + Chase-1, one block at a time. --- */
|
||||
t0 = bch_now();
|
||||
{
|
||||
uint8_t *cand_blob = xmalloc(blob_size ? blob_size : 1);
|
||||
size_t vi;
|
||||
for (vi = 0; vi < (size_t)nfail_idx; vi++) {
|
||||
size_t bi = vary[vi];
|
||||
int added0 = pools[bi].n;
|
||||
int added1;
|
||||
int k;
|
||||
/* Pass-2 candidates first (cheap). */
|
||||
{
|
||||
uint8_t *bc = malloc((size_t)BCH_PASS2_MAX_CANDS *
|
||||
(bdlen[bi] ? bdlen[bi] : 1));
|
||||
int nbc = 0, q;
|
||||
size_t s_off = 0;
|
||||
size_t j;
|
||||
for (j = 0; j < bi; j++)
|
||||
s_off += bslen[j];
|
||||
if (bc) {
|
||||
nbc = bch_decode_block_candidates(
|
||||
bch_stored + s_off, bslen[bi], bdlen[bi], poly,
|
||||
bc, BCH_PASS2_MAX_CANDS);
|
||||
for (q = 0; q < nbc && pools[bi].n < DEEP_MAX_BLOCK_CANDS; q++)
|
||||
pool_add(&pools[bi], bdlen[bi],
|
||||
bc + (size_t)q * bdlen[bi], &pool_bytes);
|
||||
}
|
||||
free(bc);
|
||||
}
|
||||
added1 = pools[bi].n; /* pool size after pass-2 */
|
||||
/* Chase-1 candidates (suspects first, then scan). */
|
||||
{
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
uint8_t *cc = malloc((size_t)BCH_CHASE_MAX_CANDS *
|
||||
(bdlen[bi] ? bdlen[bi] : 1));
|
||||
bch_chase_stats_t cs;
|
||||
int ns = 0, ncc = 0, q;
|
||||
size_t s_off = 0;
|
||||
size_t j;
|
||||
for (j = 0; j < bi; j++)
|
||||
s_off += bslen[j];
|
||||
if (susp && cc) {
|
||||
ns = bch_suspect_positions(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi],
|
||||
poly, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
ncc = bch_chase1_block(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi], poly,
|
||||
cc, BCH_CHASE_MAX_CANDS,
|
||||
susp, ns, &cs, deadline);
|
||||
stats->trials[1] += cs.trials;
|
||||
stats->split_pass[1] += cs.split_pass;
|
||||
stats->codewords[1] += cs.codewords;
|
||||
if (cs.partial)
|
||||
stats->partial = 1;
|
||||
/* Try the Chase-1 candidates DIRECTLY, in
|
||||
* scan order, before pooling: the pool cap
|
||||
* would truncate the list, and the true
|
||||
* candidate can arrive late in scan order
|
||||
* (wrong-but-valid codewords accumulate at
|
||||
* ~1 per 32K trials, so on a 4M-bit block
|
||||
* the genuine candidate can be the 20th+
|
||||
* one returned). Pooling first and trying
|
||||
* only the pooled prefix lost it. Pool
|
||||
* afterwards for the L3 list. */
|
||||
for (q = 0; q < ncc; q++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
cc + (size_t)q * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
if (try_blob(cand_blob, blob_size, level,
|
||||
want_sha, want_crc16, stats,
|
||||
&out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 1;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(susp);
|
||||
free(cc);
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
pool_add(&pools[bi], bdlen[bi],
|
||||
cc + (size_t)q * bdlen[bi], &pool_bytes);
|
||||
}
|
||||
}
|
||||
free(susp);
|
||||
free(cc);
|
||||
}
|
||||
/* Try the pass-2 candidates pooled above (added0 to
|
||||
* the pool size after pass-2; the Chase-1 candidates
|
||||
* were already tried directly). */
|
||||
for (k = added0; k < added1; k++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
pools[bi].cands + (size_t)k * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
if (try_blob(cand_blob, blob_size, level, want_sha,
|
||||
want_crc16, stats, &out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 1;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
}
|
||||
if (!retain_pools)
|
||||
pool_free(&pools[bi], &pool_bytes);
|
||||
if (bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
free(cand_blob);
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
goto bch_fail;
|
||||
}
|
||||
}
|
||||
free(cand_blob);
|
||||
}
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
if (max_level < 2)
|
||||
goto bch_fail;
|
||||
|
||||
/* --- L2: Chase-2 pairs, one block at a time. --- */
|
||||
t0 = bch_now();
|
||||
{
|
||||
uint8_t *cand_blob = xmalloc(blob_size ? blob_size : 1);
|
||||
size_t vi;
|
||||
for (vi = 0; vi < (size_t)nfail_idx; vi++) {
|
||||
size_t bi = vary[vi];
|
||||
{
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
uint8_t *cc = malloc((size_t)BCH_CHASE_MAX_CANDS *
|
||||
(bdlen[bi] ? bdlen[bi] : 1));
|
||||
bch_chase_stats_t cs;
|
||||
int ns = 0, ncc = 0, q;
|
||||
size_t s_off = 0;
|
||||
size_t j;
|
||||
for (j = 0; j < bi; j++)
|
||||
s_off += bslen[j];
|
||||
if (susp && cc) {
|
||||
ns = bch_suspect_positions(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi],
|
||||
poly, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
ncc = bch_chase2_block(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi], poly,
|
||||
cc, BCH_CHASE_MAX_CANDS,
|
||||
susp, ns, &cs, deadline);
|
||||
stats->trials[2] += cs.trials;
|
||||
stats->split_pass[2] += cs.split_pass;
|
||||
stats->codewords[2] += cs.codewords;
|
||||
if (cs.partial)
|
||||
stats->partial = 1;
|
||||
/* Try the Chase-2 candidates directly (the
|
||||
* pool may already be full from L1, so
|
||||
* pooling first would starve them); pool
|
||||
* each afterwards for the L3 list. */
|
||||
for (q = 0; q < ncc; q++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
cc + (size_t)q * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
if (try_blob(cand_blob, blob_size, level,
|
||||
want_sha, want_crc16, stats,
|
||||
&out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 2;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[2] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(susp);
|
||||
free(cc);
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
pool_add(&pools[bi], bdlen[bi],
|
||||
cc + (size_t)q * bdlen[bi], &pool_bytes);
|
||||
}
|
||||
}
|
||||
free(susp);
|
||||
free(cc);
|
||||
}
|
||||
if (!retain_pools)
|
||||
pool_free(&pools[bi], &pool_bytes);
|
||||
if (bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
free(cand_blob);
|
||||
stats->t_level[2] = bch_now() - t0;
|
||||
goto bch_fail;
|
||||
}
|
||||
}
|
||||
free(cand_blob);
|
||||
}
|
||||
stats->t_level[2] = bch_now() - t0;
|
||||
if (max_level < 3)
|
||||
goto bch_fail;
|
||||
|
||||
/* --- L3: two failing blocks varied at once (list). --- */
|
||||
t0 = bch_now();
|
||||
if (nfail >= 2 && retain_pools) {
|
||||
uint8_t *cand_blob = xmalloc(blob_size ? blob_size : 1);
|
||||
long tried3 = 0;
|
||||
size_t ai, bj;
|
||||
for (ai = 0; ai < (size_t)nfail_idx && tried3 < DEEP_MAX_BLOB_CANDS; ai++) {
|
||||
size_t bi = vary[ai];
|
||||
for (bj = ai + 1; bj < (size_t)nfail_idx && tried3 < DEEP_MAX_BLOB_CANDS; bj++) {
|
||||
size_t bk = vary[bj];
|
||||
int ci, cj;
|
||||
if (pools[bi].n == 0 || pools[bk].n == 0)
|
||||
continue;
|
||||
for (ci = 0; ci < pools[bi].n && tried3 < DEEP_MAX_BLOB_CANDS; ci++) {
|
||||
for (cj = 0; cj < pools[bk].n && tried3 < DEEP_MAX_BLOB_CANDS; cj++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
pools[bi].cands + (size_t)ci * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
memcpy(cand_blob + boff[bk],
|
||||
pools[bk].cands + (size_t)cj * bdlen[bk],
|
||||
bdlen[bk]);
|
||||
tried3++;
|
||||
if (try_blob(cand_blob, blob_size, level,
|
||||
want_sha, want_crc16, stats,
|
||||
&out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 3;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[3] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
if ((tried3 & 15) == 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
free(cand_blob);
|
||||
stats->t_level[3] = bch_now() - t0;
|
||||
goto bch_fail;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
free(cand_blob);
|
||||
}
|
||||
stats->t_level[3] = bch_now() - t0;
|
||||
|
||||
bch_fail:
|
||||
if (stats->partial && bch_now() > deadline)
|
||||
strcpy(stats->fail_stage, "budget");
|
||||
else if (stats->cands_tried == 0)
|
||||
strcpy(stats->fail_stage, "nocand");
|
||||
else if (stats->crc_rejects == stats->cands_tried)
|
||||
strcpy(stats->fail_stage, "crc");
|
||||
else
|
||||
strcpy(stats->fail_stage, "sha");
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = -1;
|
||||
goto bch_cleanup;
|
||||
|
||||
bch_done:
|
||||
/* Bits corrected at the landing level: re-encode the WINNING
|
||||
* blob (`won`, the candidate that verified) and count bit
|
||||
* differences against the received BCH bytes -- exact for
|
||||
* L1+ (the re-encoded true codeword differs from the
|
||||
* received word exactly at the error positions). L0 uses
|
||||
* the pass-1 corrected count. */
|
||||
if (stats->level_landed > 0) {
|
||||
size_t elen = bch_encoded_len(blob_size, poly);
|
||||
uint8_t *enc = malloc(elen ? elen : 1);
|
||||
if (enc && bch_encode(won, blob_size, poly, enc) == elen)
|
||||
stats->bch_corrected = (int)count_bit_diffs(
|
||||
enc, bch_stored, elen < bch_len ? elen : bch_len);
|
||||
free(enc);
|
||||
}
|
||||
/* level 0 already set bch_corrected = corr_total. */
|
||||
|
||||
bch_cleanup:
|
||||
for (i = 0; i < nblocks; i++)
|
||||
pool_free(&pools[i], &pool_bytes);
|
||||
free(boff);
|
||||
free(bdlen);
|
||||
free(bslen);
|
||||
free(ok);
|
||||
free(base);
|
||||
free(won);
|
||||
free(pools);
|
||||
free(vary);
|
||||
free(bch_owned);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
/* deep_repair.h - escalating repair past the BCH limit t.
|
||||
*
|
||||
* The ladder, per entry (see docs/deep-repair.md for the full
|
||||
* design, bounds, and measured numbers):
|
||||
* L0: standard decode to t (BCH pass 1, plus RS first for LZRS).
|
||||
* L1: pass-2 candidates + Chase-1 single-bit flips (suspects
|
||||
* first, then an exhaustive scan of the failing block).
|
||||
* L2: Chase-2 two-bit flips (pairs within the suspect set, then
|
||||
* (suspect, any-position) pairs).
|
||||
* L3: bounded list decoding across blocks: candidate blobs formed
|
||||
* by varying TWO failing blocks at once, from the pooled
|
||||
* per-block candidates of L1+L2.
|
||||
* Every candidate blob is CRC16-checked before the expensive
|
||||
* decompress + SHA-256 step; the CRC16 is the fast oracle and the
|
||||
* SHA-256 is the final oracle. Nothing is ever returned unless it
|
||||
* passes both. Expected residual false-accept is ~2^-16 per
|
||||
* candidate at the CRC stage (the SHA-256 stage then gates
|
||||
* acceptance).
|
||||
*
|
||||
* Bounds (enforced, not aspirational): per-block candidate pools
|
||||
* are capped (8 Chase-1 + 8 Chase-2 candidates per block), L3 tries
|
||||
* at most 256 candidate blobs, retained pool memory is capped at
|
||||
* 128 MiB, and the whole entry is capped by a wall-clock budget
|
||||
* (default 120 s). stats.partial says when a level stopped early
|
||||
* on its budget, and stats.trials says how far the scan got.
|
||||
* Per-level timing is reported in stats.t_level -- that is the
|
||||
* "time of arrival": how long each level took, and which level the
|
||||
* repair landed at.
|
||||
*/
|
||||
#ifndef LZPLY_DEEP_REPAIR_H
|
||||
#define LZPLY_DEEP_REPAIR_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Highest repair level. */
|
||||
#define DEEP_MAX_LEVEL 3
|
||||
/* Default wall-clock budget per entry, seconds. */
|
||||
#define DEEP_DEFAULT_BUDGET_SEC 120.0
|
||||
/* Max candidate blobs combined at L3. */
|
||||
#define DEEP_MAX_BLOB_CANDS 256
|
||||
/* Max per-block candidates pooled per level source (L1, L2). */
|
||||
/* Maximum candidates retained per block in the L3 pool. The pool
|
||||
* holds up to 2x this many (pass-2 plus Chase candidates); the
|
||||
* Chase levels try their candidates directly, so this cap only
|
||||
* bounds what L3 can combine. 32 keeps a genuine candidate that
|
||||
* arrives late in scan order (see deep_repair.c L1) while the
|
||||
* 128 MiB pool byte cap bounds memory. */
|
||||
#define DEEP_MAX_BLOCK_CANDS 32
|
||||
/* Max retained pool memory across blocks, bytes. */
|
||||
#define DEEP_MAX_POOL_BYTES (128u * 1024u * 1024u)
|
||||
|
||||
typedef struct {
|
||||
int level_landed; /* -1 failed, else 0..3 */
|
||||
int rs_corrected; /* RS symbols corrected (LZRS only) */
|
||||
int bch_corrected; /* BCH bits corrected at the landing level
|
||||
(-1 when not computed) */
|
||||
long cands_tried; /* candidate blobs CRC-checked */
|
||||
long crc_rejects; /* candidates failing CRC16 */
|
||||
long sha_rejects; /* candidates passing CRC but failing
|
||||
decompression / SHA-256 */
|
||||
long trials[4]; /* Chase BM trials per level */
|
||||
long split_pass[4]; /* trials passing the splitting filter */
|
||||
long codewords[4]; /* trials yielding a valid codeword */
|
||||
double t_level[4]; /* seconds spent per level */
|
||||
double t_total; /* seconds for the whole entry */
|
||||
long blocks_total; /* BCH blocks in the blob */
|
||||
long blocks_failed; /* blocks failing standard decode */
|
||||
int partial; /* a level stopped early on its budget */
|
||||
char fail_stage[24]; /* "ok", "rs", "len", "crc", "sha",
|
||||
"budget", "noecc", "nocand" */
|
||||
} deep_stats_t;
|
||||
|
||||
/* Attempt the escalating repair of one archive entry.
|
||||
* `stored` / `stored_len` are the entry's stored bytes (RS-encoded
|
||||
* when rs_level > 0), `level` the lzip level, `is_bch` / `poly_id`
|
||||
* / `rs_level` from the entry header, `want_sha` the entry's
|
||||
* SHA-256, `blob_size` the pre-ECC blob length, `want_crc16` the
|
||||
* entry header's CRC16. `max_level` caps the ladder (0..3);
|
||||
* `budget_sec` is the wall-clock budget for this entry (<= 0
|
||||
* means the default). On success returns 0 with *raw / *raw_len
|
||||
* the recovered bytes and stats.level_landed set; on failure
|
||||
* returns -1 with stats.fail_stage set. Stats are zeroed on entry
|
||||
* (NULL is allowed). */
|
||||
int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id, int rs_level,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint16_t want_crc16, int max_level, double budget_sec,
|
||||
uint8_t **raw, size_t *raw_len, deep_stats_t *stats);
|
||||
|
||||
#endif /* LZPLY_DEEP_REPAIR_H */
|
||||
@@ -1,321 +0,0 @@
|
||||
# lzply baseline — experiments/baseline @ 8dbb8d03
|
||||
|
||||
Measured 2026-12-02 on hot_newyork (172.93.49.176, 8 cores, 30 GB RAM,
|
||||
Ubuntu 26.04.1, gcc 15.2.0, liblz 1.16~rc1, libfuse3 3.18.2).
|
||||
Base commit: `8dbb8d03` — "BCH: two-pass silent repair (hash-gated pass 2;
|
||||
zero silent failures, loud failure otherwise)".
|
||||
Branch: `experiments/baseline`. This file is the yardstick for the
|
||||
parallel ECC / compression experiments: same corpus, same commands,
|
||||
same harness (`bench/`).
|
||||
|
||||
## 1. Codebase map
|
||||
|
||||
Repo root `/opt/lzply-exp-base` (checked out from
|
||||
`git@github.com:cnmcdee/lzply.git`, branch `experiments/baseline`).
|
||||
~11,633 lines of C/Python, no legacy support: v4 (`LZPL`) is the only
|
||||
format; v1/v2/v3 and old magics `LZRS`/`LZBC` are rejected outright.
|
||||
|
||||
| File | Lines | Role |
|
||||
|---|---|---|
|
||||
| `lzply.c` | 1926 | `lzply` CLI: `-c/-a/-d/-l/-t/-i/-tr`, date filters, selectors |
|
||||
| `lzply_lib.c` / `lzply_lib.h` | 930 / 253 | shared core: v4 format, per-entry pipeline (lzip -> BCH), header I/O, archive scan, filters |
|
||||
| `bch.c` / `bch.h` | 1007 / 109 | binary BCH codec + two-pass (pass-2 candidate) repair |
|
||||
| `bch_polys.h` | 273 | 82 embedded generator polynomials (parents N = 2^m - 1, m = 7..22) |
|
||||
| `gen_bch_polys.py` | 322 | regenerates `bch_polys.h` from rssearch data (checked in, not rebuilt by make) |
|
||||
| `bch_test.c` | 415 | BCH unit tests (table remainder vs brute force, roundtrips, corruption, auto-pick, block splitting) |
|
||||
| `sha256.c` / `sha256.h` | 124 / 26 | SHA-256 (per-entry integrity; load-bearing against BCH miscorrection) |
|
||||
| `lzply_mount.c` | 1448 | FUSE filesystem (`lzply_mount`, `mount.lzply` helper) |
|
||||
| `lzply_stat.c` | 293 | per-entry statistics (sizes, poly, t, parity bits, ECC overhead %) |
|
||||
| `lzply_heal.c` | 618 | strip + re-apply BCH parity without touching the compressed blob |
|
||||
| `lzply_check.c` | 564 | bit-error-rate measurement (`--json`, `--warn-ber`, `--fail-ber`) |
|
||||
| `lzply_refresh.c` | 410 | in-place platter refresher (1-3 passes, SHA-256 verified) |
|
||||
| `lzply_hyper.c` | 2264 | striped volume: 8 bit-plane data stripes + 1-3 XOR/GF parity, rebuilds up to 3 dead stripes (no compression) |
|
||||
| `lzply_util.c` / `lzply_util.h` | 440 / 33 | shared helpers for stat/heal/check/refresh (mount resolution via /proc, human sizes) |
|
||||
| `lzprobe.c` | 41 | tiny probe tool |
|
||||
| `Makefile` | 137 | builds 7 binaries + `bch_test`; `make test` runs the full suite |
|
||||
| `tests/run_tests.sh` | 1156 | 147 archive tests (see §3) |
|
||||
| `tests/run_hyper_tests.sh` | 443 | 56 striped-volume tests |
|
||||
| `tests/corrupt.c`, `tests/corrupt_bits.c` | 96 / 103 | whole-byte / single-bit corruption injectors used by the suite |
|
||||
| `tests/make_testdata.sh` | 46 | generates `testdata/` (incl. a 50 MiB random file) on demand |
|
||||
| `bench/bench.sh` | — | this baseline's ratio/speed/memory benchmark (see §5) |
|
||||
| `bench/corrupt_matrix.py` | — | this baseline's corruption matrix (see §6) |
|
||||
| `README.md`, `README-hyper.md`, `lzply_hyper-design.md` | — | user docs; format + CLI reference |
|
||||
|
||||
Build system: plain `make` (no configure/autotools). `make -j8` builds
|
||||
`lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh
|
||||
lzply_hyper` + `liblzply.a` (lzply_lib + bch + sha256). Deps:
|
||||
`build-essential`, `liblz-dev` (lzip/LZMA), `libfuse3-dev` (mount only).
|
||||
`CFLAGS = -O2 -Wall -Wextra`; the baseline build is warning-clean.
|
||||
|
||||
## 2. Format (v4) and pipeline
|
||||
|
||||
All integers little-endian. Global header (16 B): magic `"LZPL"`,
|
||||
version u8 (=4), flags u8, entry_count u32, reserved u64. Each entry:
|
||||
u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
u32 mode, u64 mtime, u32 header_crc32 (covers the 74 bytes before it),
|
||||
path[path_len], data[stored_size]. End marker: u16 path_len == 0.
|
||||
|
||||
Per-entry pipeline: `compress (lzip) -> BCH encode` on write;
|
||||
`BCH-decode -> decompress` on read. One entry = one independent byte
|
||||
stream. `blob_size` is the compressed length before ECC parity.
|
||||
|
||||
CLI (see `README.md` for the full reference):
|
||||
|
||||
- Compression: lzip levels `-1`..`-9`, default `-6`. The compressed
|
||||
stream inside an entry is byte-identical to `lzip -N`.
|
||||
- Store mode (level 0): when the compressed blob would be no smaller
|
||||
than the original (already-compressed / random / empty), the entry is
|
||||
stored uncompressed; BCH still applies. `-0` forces store for all.
|
||||
- Error correction: `-e <0..7>` maps to BCH t: 0 -> none, 1 -> 1,
|
||||
2 -> 2, 3 -> 4, 4 -> 8, 5 -> 16, 6 -> 32, 7 -> 32. Default `-e 4`
|
||||
(t=8). `poly=NN` (hex `poly=003a` or decimal `poly=58`) pins one
|
||||
polynomial and overrides `-e`. With no pin, the most efficient poly
|
||||
for the blob length is auto-picked (smallest parent whose codeword
|
||||
covers the blob). A blob longer than one block's capacity is split
|
||||
into blocks of that poly's max payload (m=22, t=32: 524,199 B/block);
|
||||
the decoder rebuilds boundaries from blob_size + poly.
|
||||
- Integrity: every entry carries SHA-256 of its original data. A
|
||||
bounded-distance BCH decoder can miscorrect damage beyond t (e.g.
|
||||
t=1, 2-bit errors miscorrect ~50% at codec level); SHA-256 catches
|
||||
it, so miscorrection is reported as corruption, never silent damage.
|
||||
- Two-pass repair (this base commit): when pass-1 decode fails (or the
|
||||
hash fails after a pass-1 success), pass 2 enumerates up to 16
|
||||
candidate decodings (residual-BM + bounded flip-and-redecode) and the
|
||||
caller hash-verifies each; first SHA-256 match wins, otherwise loud
|
||||
failure. Zero silent failures by construction.
|
||||
- Timestamps: mtime (seconds, UTC) + file mode stored per entry;
|
||||
ownership not stored. `-datestart` / `-dateend` / `-year` filter on
|
||||
mtime; `-i` reads headers only (never decompresses); `-tr` prints a
|
||||
tree; `-a` appends (incremental when no path collides); selectors
|
||||
match exact paths or directory prefixes.
|
||||
- Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.
|
||||
- Limitations (v4): whole files buffered in memory (50 MiB fine,
|
||||
multi-GB needs a streaming rewrite); symlinks/special files skipped;
|
||||
BCH corrects scattered bit flips, not whole lost bytes — a burst
|
||||
wiping many consecutive bits in one block can exceed t even when the
|
||||
byte count is small; the BCH decoder builds GF(2^m) log/exp tables
|
||||
(up to 32 MiB transient for m=22) the first time it must correct an
|
||||
error in a block (no-error path needs no tables).
|
||||
|
||||
## 3. Test suite — results at this base
|
||||
|
||||
`make test` = `bch_test` + `tests/run_tests.sh` + `tests/run_hyper_tests.sh`.
|
||||
|
||||
| Suite | Result (hot_newyork) |
|
||||
|---|---|
|
||||
| `bch_test` phase 1+2 (remainder x-check + roundtrip, all 82 polys) | 5220 checks, 0 fails |
|
||||
| `bch_test` phase 3 (corruption) | 7253 checks, 0 fails |
|
||||
| `tests/run_tests.sh` | **147 passed, 0 failed** |
|
||||
| `tests/run_hyper_tests.sh` | **56 passed, 0 failed** |
|
||||
|
||||
Coverage: roundtrips at every level `-1`..`-9`; byte-identical
|
||||
cross-check vs system `lzip -6` (at `-e 0`); roundtrips at BCH levels
|
||||
0..7; BCH corruption with pinned polys (t recovered, t+1 fails
|
||||
cleanly); combined `-9 -e 5` with 16 corrupted bits; v1/v3 archives
|
||||
and old magics rejected; overwrite flags; empty dir/file, 1-byte file,
|
||||
spaces in names, truncated/non-archive inputs; 50 MiB multi-block file;
|
||||
`poly=` pinning (hex/decimal), unknown-poly rejection; append (21
|
||||
tests) + selective extract; inspect/tree/date filters (27 tests);
|
||||
`lzply_stat` (4), `lzply_heal` (8), `lzply_check` (8),
|
||||
`lzply_refresh` (9), mount write-back (3), store mode (16).
|
||||
|
||||
Environment caveat (NOT a code failure): run from `/opt/lzply-exp-base`
|
||||
the suite reports **144 passed, 3 failed** — the 3 mount write-back
|
||||
tests (`mount with relative archive path: writes persist in the real
|
||||
archive`, `store mode: mount repack stores an incompressible file`,
|
||||
`store mode: mount-repacked stored file extracts byte-identical`).
|
||||
Root cause, verified: AppArmor's `fusermount3` profile (enforce mode,
|
||||
`/etc/apparmor.d/fusermount3`) allows `umount` only under
|
||||
`@{HOME}/**`, `/mnt/**`, `/run/user/@{uid}/**`, `/media/**`,
|
||||
`/tmp/**`, `/cvmfs/**` — NOT under `/opt/**`. `fusermount3 -u`
|
||||
fails with EPERM (audit: `apparmor="DENIED" operation="umount" ...
|
||||
profile="fusermount3"`), the mount stays up, the repack never runs,
|
||||
and the test reads the pre-mount archive. The lzply code is correct:
|
||||
the same tests pass when the tree is copied under `/tmp`
|
||||
(147/0 above), a manual relative-path mount under `/tmp` repacks
|
||||
correctly, and plain `umount` (unconfined) unmounts the `/opt` mounts
|
||||
fine and triggers the repack. To run the suite green, run it from a
|
||||
copy under `/tmp` (or any AppArmor-allowed path):
|
||||
`cp -a /opt/lzply-exp-base /tmp/lzply-tmproot && cd /tmp/lzply-tmproot && make test`.
|
||||
Stale mounts left by the failing `/opt` runs were cleaned with
|
||||
`umount` (the other coordinator's `/opt/lzply-exp-ecc` mounts were
|
||||
left untouched).
|
||||
|
||||
## 4. Corpus (reproduction)
|
||||
|
||||
Standard corpora, downloaded 2026-12-02 to `/opt/lzply-bench/corpus/`:
|
||||
|
||||
- `enwik8` — first 100,000,000 bytes of English Wikipedia
|
||||
(https://mattmahoney.net/dc/enwik8.zip), sha256
|
||||
`2b49720ec4d78c3c9fabaee6e4179a5e997302b3a70029f30f2d582218c024a8`
|
||||
- Silesia corpus (https://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip),
|
||||
all 12 files:
|
||||
|
||||
| file | bytes | sha256 |
|
||||
|---|---|---|
|
||||
| dickens | 10,192,446 | `b24c37886142e11d0ee687db6ab06f936207aa7f2ea1fd1d9a36763c7a507e6a` |
|
||||
| mozilla | 51,220,480 | `657fc3764b0c75ac9de9623125705831ebbfbe08fed248df73bc2dc66e2a963b` |
|
||||
| mr | 9,970,564 | `68637ed52e3e4860174ed2dc0840ac77d5f1a60abbcb13770d5754e3774d53e6` |
|
||||
| nci | 33,553,445 | `fc63a31770947b8c2062d3b19ca94c00485a232bb91b502021948fee983e1635` |
|
||||
| ooffice | 6,152,192 | `e7ee013880d34dd5208283d0d3d91b07f442e067454276095ded14f322a656eb` |
|
||||
| osdb | 10,085,684 | `60f027179302ca3ad87c58ac90b6be72ec23588aaa7a3b7fe8ecc0f11def3fa3` |
|
||||
| reymont | 6,627,202 | `0eac0114a3dfe6e2ee1f345a0f79d653cb26c3bc9f0ed79238af4933422b7578` |
|
||||
| samba | 21,606,400 | `93ba07bc44d8267789c1d911992f40b089ffa2140b4a160fac11ccae9a40e7b2` |
|
||||
| sao | 7,251,944 | `c2d0ea2cc59d4c21b7fe43a71499342a00cbe530a1d5548770e91ecd6214adcc` |
|
||||
| webster | 41,458,703 | `6a68f69b26daf09f9dd84f7470368553194a0b294fcfa80f1604efb11143a383` |
|
||||
| x-ray | 8,474,240 | `7de9fce1405dc44ae5e6813ed21cd5751e761bd4265655a005d39b9685d1c9ad` |
|
||||
| xml | 5,345,280 | `0e82e54e695c1938e4193448022543845b33020c8be6bf3bf3ead2224903e08c` |
|
||||
|
||||
Data files total 311,489,800 bytes. The corpus directory also holds the
|
||||
two source zips (`enwik8.zip` 36,445,475 B, `silesia.zip` 68,182,744 B);
|
||||
whole-directory runs archive all 15 files (416,566,799 B total).
|
||||
Corruption-matrix input: `slice1m.bin` = first 1,048,576 bytes of
|
||||
`enwik8`, sha256
|
||||
`4fb5efa9f35df431737731bf3c8f38a467b69731940ff82a4ee0e218aae58834`,
|
||||
archived as `slice1m.lzply` at `-6 -e 4` (blob 296.9 KiB, poly `0050`,
|
||||
t=8, single BCH block; 176 parity bits, 0.007% ECC overhead).
|
||||
|
||||
Reproduce the corpus download:
|
||||
|
||||
```sh
|
||||
mkdir -p /opt/lzply-bench/corpus && cd /opt/lzply-bench/corpus
|
||||
curl -sL -o enwik8.zip https://mattmahoney.net/dc/enwik8.zip
|
||||
curl -sL -o silesia.zip https://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip
|
||||
python3 -c "import zipfile; zipfile.ZipFile('enwik8.zip').extractall()"
|
||||
python3 -c "import zipfile; zipfile.ZipFile('silesia.zip').extractall()"
|
||||
sha256sum enwik8 dickens mozilla mr nci ooffice osdb reymont samba sao webster x-ray xml
|
||||
```
|
||||
|
||||
## 5. Baseline numbers — ratio, speed, memory
|
||||
|
||||
Command: `bench/bench.sh <lzply> <corpus-dir> <work-dir>` (needs
|
||||
GNU `time`, `/usr/bin/time -v`, for wall clock + max RSS). Each run:
|
||||
one encode, one decode, `diff -r` round-trip check. Machine shared
|
||||
with other agents' builds during measurement — encode wall times are
|
||||
noisy (see caveat); decode is stable. All round-trips bit-identical.
|
||||
|
||||
### 5.1 enwik8, single file, 100,000,000 bytes, default -e 4 (t=8)
|
||||
|
||||
| level | archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| -1 | 29,126,665 | 29.13% | 1:43.82 | 0.96 | 156,404 KB | 0:06.57 | 15.2 | 157,560 KB |
|
||||
| -6 | 26,519,665 | 26.52% | 3:06.14 | 0.54 | 215,800 KB | 0:06.19 | 16.2 | 159,668 KB |
|
||||
| -9 | 25,397,987 | 25.40% | 4:10.43 | 0.40 | 485,112 KB | 0:06.24 | 16.0 | 181,880 KB |
|
||||
|
||||
### 5.2 whole corpus directory, 416,566,799 bytes (15 files), -6
|
||||
|
||||
| -e (t) | archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| 4 (t=8, default) | 181,121,579 | 43.48% | 8:54.98 | 0.78 | 242,384 KB | 0:22.28 | 18.7 | 233,832 KB |
|
||||
| 0 (no ECC) | 181,113,835 | 43.48% | 8:33.81 | 0.81 | 242,444 KB | 0:17.31 | 24.1 | 177,976 KB |
|
||||
| 7 (t=32) | 181,144,811 | 43.49% | 8:56.79 | 0.78 | 242,568 KB | 0:38.93 | 10.7 | 233,844 KB |
|
||||
|
||||
ECC overhead on this corpus: default t=8 costs 7,744 bytes over no-ECC
|
||||
(0.0043%); t=32 costs 30,976 bytes (0.017%). BCH parity is negligible
|
||||
next to LZMA output at these sizes — the overhead story is per-block
|
||||
parity bits, not a percentage of the archive. Decode slows with t
|
||||
(17.3s -> 22.3s -> 38.9s) because larger t means larger GF tables on
|
||||
the correction path and more blocks to check.
|
||||
|
||||
### 5.3 mozilla (binary-ish), 51,220,480 bytes, -6 -e 4
|
||||
|
||||
| archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| 13,580,691 | 26.51% | 0:49.45 | 1.04 | 155,768 KB | 0:02.89 | 17.7 | 86,776 KB |
|
||||
|
||||
### 5.4 Caveats
|
||||
|
||||
- Encode speed is dominated by single-threaded LZMA (`liblz`), not by
|
||||
BCH: `-1` vs `-9` on enwik8 is 0.96 vs 0.40 MB/s for a 29.1% ->
|
||||
25.4% ratio gain. Any compression-family experiment must beat
|
||||
these ratio/speed points, not just the ratio.
|
||||
- Wall times were measured while other agents were building on the
|
||||
same 8-core server; expect encode times to vary run to run. Decode
|
||||
times (I/O + LZMA decode, single-threaded) were stable across runs.
|
||||
- Peak RSS is dominated by the whole-file buffering (input + blob +
|
||||
stored copy in memory at once) plus, at `-9`, LZMA's dictionary
|
||||
(485 MB for enwik8 -9 encode). Multi-GB files need the streaming
|
||||
rewrite noted in §2.
|
||||
|
||||
## 6. Corruption matrix — correction power at default -e 4 (t=8)
|
||||
|
||||
Harness: `bench/corrupt_matrix.py <lzply> <archive> <trials> [seed]`.
|
||||
Single-entry archive `slice1m.lzply` (see §4: 1 MiB text, blob
|
||||
296.9 KiB, one BCH block, t=8). Each trial: copy the archive, corrupt
|
||||
ONLY the stored-data region (headers untouched), run `lzply -t`, and
|
||||
on success extract + SHA-256-verify the recovered file. 200 trials
|
||||
per setting, seed 20261202 (Python `random.Random`, deterministic).
|
||||
"recovered" = `-t` passed AND extracted bytes hash-identical;
|
||||
"failed-loud" = `-t` (or extract) exited non-zero; "silent-bad" =
|
||||
passed but content wrong (must be 0 — the SHA-256 gate).
|
||||
|
||||
### 6.1 Results (200 trials per setting)
|
||||
|
||||
Scattered bits (seed 20261202), single 304 KB block, t=8:
|
||||
|
||||
| scattered bits flipped | recovered | failed-loud | silent-bad |
|
||||
|---|---|---|---|
|
||||
| 1 | 200/200 | 0 | 0 |
|
||||
| 2 | 200/200 | 0 | 0 |
|
||||
| 4 | 200/200 | 0 | 0 |
|
||||
| 8 (= t) | 200/200 | 0 | 0 |
|
||||
| 9 (= t+1) | **0/200** | 200 | 0 |
|
||||
| 16 | **0/200** | 200 | 0 |
|
||||
| 32 | **0/200** | 200 | 0 |
|
||||
|
||||
Bursts — L consecutive bytes replaced with random bytes (up to 8L bit
|
||||
errors); two independent seeds:
|
||||
|
||||
| burst length | recovered (seed 20261202) | recovered (seed 20261203) | failed-loud | silent-bad |
|
||||
|---|---|---|---|---|
|
||||
| 1 byte | 200/200 | 200/200 | 0 | 0 |
|
||||
| 2 bytes | 135/200 | 117/200 | 65 / 83 | 0 |
|
||||
| 4 bytes | 0/200 | 0/200 | 200 | 0 |
|
||||
| 8 bytes | 0/200 | 0/200 | 200 | 0 |
|
||||
| 16 bytes | 0/200 | 0/200 | 200 | 0 |
|
||||
|
||||
**Total silent-bad across all 2,800 trials: 0.** The SHA-256 gate
|
||||
holds everywhere: damage beyond t is always a loud failure, never
|
||||
wrong data.
|
||||
|
||||
### 6.2 Reading the numbers
|
||||
|
||||
- The cliff is exactly at t: everything at or below 8 scattered bit
|
||||
errors recovers; everything above recovers nothing. Pass 1
|
||||
(bounded-distance BCH) behaves exactly as theory says.
|
||||
- **Pass 2 rescues nothing beyond t for random scattered errors at
|
||||
this block size: 0/600 trials at n = 9, 16, 32.** Pass 2 IS wired
|
||||
in (`entry_decode` in `lzply_lib.c` calls `bch_decode_candidates`,
|
||||
up to 16 candidates, hash-gated) — the residual-BM +
|
||||
flip-and-redecode candidates simply never land on the true codeword
|
||||
for random t+1..t+4 patterns in a 304 KB (m=22) block. This is the
|
||||
gap the deep-repair work (Chase flips, list decoding) exists to
|
||||
close; any experiment claiming beyond-t recovery must beat 0/200
|
||||
here, on this archive, with these seeds.
|
||||
- The 2-byte burst split (117-135/200) is the binomial edge: two
|
||||
random bytes differ in ~8 bits on average, so about half the trials
|
||||
land at <= 8 bit errors (recovered) and half above (failed). A
|
||||
1-byte burst is always <= 8 bit errors, hence 200/200.
|
||||
- Pass 2 is expensive when it runs: trials at n <= 8 cost ~1 s each
|
||||
(fresh `lzply -t` + `lzply -d` processes, GF(2^22) table build on
|
||||
the correction path); trials beyond t cost ~4-5 s each (candidate
|
||||
enumeration). A repair scheme's per-block time budget matters as
|
||||
much as its recovery rate.
|
||||
|
||||
Reproduce: `python3 bench/corrupt_matrix.py /opt/lzply-exp-base/lzply
|
||||
/opt/lzply-bench/slice1m.lzply 200 20261202` (bits + bursts, one
|
||||
process) or with `MATRIX_ONLY=burst MATRIX_WORKDIR=/tmp/lzply-matrix-burst`
|
||||
and seed 20261203 for the burst-only run. Logs:
|
||||
`/opt/lzply-bench/matrix.log`, `/opt/lzply-bench/matrix-burst.log`.
|
||||
|
||||
## 7. What is NOT in this baseline
|
||||
|
||||
- hot_chicago build/test: blocked by the sshd outage (new sessions
|
||||
hang at banner exchange; see report). The branch is pushed, so the
|
||||
Chicago run is a clone + `make -j8` + `make test` + the same
|
||||
`bench.sh` / `corrupt_matrix.py` once SSH recovers. Chicago needs
|
||||
no package installs (lzip, liblz-dev, libfuse3-dev present).
|
||||
- `lzply_hyper` (striped volume) numbers: the suite passes (56/0)
|
||||
but no separate ratio/speed benchmark was run — it stores
|
||||
uncompressed stripes, so its yardstick is rebuild time, not ratio.
|
||||
@@ -1,203 +0,0 @@
|
||||
# Integration: experiment winners on current main (LZPL v5)
|
||||
|
||||
Merged onto `experiments/integration` at `b27b345` (LZPL v5 + lz_rs +
|
||||
deep repair + CRC16). The three experiment branches were all based on
|
||||
`8dbb8d03`; this integration re-bases their winners onto current main
|
||||
instead. The archive format is unchanged (still LZPL v5): the winners
|
||||
arrive as standalone tools in `exp/` and `experiments/`, built and
|
||||
smoke-tested by `tests/run_integration_tests.sh` (hooked into
|
||||
`make test`). Wiring interleave/LDPC into `lzply -e` levels would be
|
||||
a format change (LZPL v6) and is explicitly future work, not done here.
|
||||
|
||||
## Sources
|
||||
|
||||
| branch | tip | carried over |
|
||||
|---|---|---|
|
||||
| `experiments/baseline` | `5807281` | `bench/`, `docs/BASELINE.md` (the comparison baseline) |
|
||||
| `experiments/ecc` | `a34cd7d` | `exp/` harness + interleave + LDPC (see below) |
|
||||
| `experiments/comp` | `fbce346` | `experiments/` rANS core + dict + bchcheck (see below) |
|
||||
|
||||
## Winners (integrated)
|
||||
|
||||
### 1. Byte interleaving, depth 64, over small-block BCH (`exp/`)
|
||||
|
||||
* What: the encoded stream (BCH, 1 KiB blocks) is permuted before it
|
||||
hits the channel — groups of D consecutive blocks written row-wise
|
||||
into a D-row matrix, read out column-wise. A burst of L bytes then
|
||||
hits any one block at most ceil(L/D) bytes instead of all L bytes
|
||||
landing in one block and killing it. Zero extra parity: a pure
|
||||
permutation, inverted on decode, so overhead is exactly the BCH
|
||||
overhead and random-error performance is unchanged.
|
||||
* Gotcha fixed on the branch: groups merge the short tail (a 4-block
|
||||
tail group measured 0.94 on 64 B bursts before the fix).
|
||||
* Measured (text.lz, 64 KiB windows, 200 trials/setting):
|
||||
`intlv-d64-bch1k-t32` recovers 1.00 at burst 16/64/256 B and 1.00 at
|
||||
4x64 B bursts, where uninterleaved `bch1k-t32` recovers 0.00 at every
|
||||
burst size. Random-error performance unchanged by construction
|
||||
(1.00 at BER 1e-3, same as `bch1k-t32`). Overhead 5.40%.
|
||||
Even at 1.29% overhead, `intlv-d64-bch1k-t8` survives 64 B bursts
|
||||
at 1.00.
|
||||
* Speed: interleaving costs nothing measurable (3.39 MB/s enc,
|
||||
1.73 MB/s dec — same as the BCH underneath).
|
||||
* Use:
|
||||
```
|
||||
cd exp && ./mkcorpora.sh # build corpora/text.lz etc.
|
||||
./bench --codec intlv-d64-bch1k-t32 --blob corpora/text.lz \
|
||||
--size 65536 --trials 200 --burst 256,1 --out results/x.csv
|
||||
```
|
||||
|
||||
### 2. Small-block BCH, 1 KiB blocks (`exp/`)
|
||||
|
||||
* What: the same BCH lzply ships, but forced to m=13 blocks
|
||||
(971 data bytes/block) instead of one huge block per blob.
|
||||
This is the "spend real redundancy" point.
|
||||
* Measured (text.lz, 64 KiB, 200 trials): `bch1k-t32` recovers 1.00
|
||||
at BER 1e-4 and 1e-3, 0.01 at 3e-3, at 5.40% overhead — where
|
||||
as-shipped `bch-t32` (one 64 KiB block, 0.12% overhead) recovers
|
||||
1.00 at 1e-5, 0.01 at 1e-4, 0.00 at 1e-3. Bursts still kill it
|
||||
without interleaving (256 B burst: 0.00 at every t).
|
||||
* Speed: `bch1k-t32` 2.97 MB/s enc, 1.55 MB/s dec;
|
||||
`bch1k-t8` 9.98 / 5.87 MB/s at 1.29% overhead.
|
||||
* Use:
|
||||
```
|
||||
./bench --codec bch1k-t32 --blob corpora/text.lz \
|
||||
--size 65536 --trials 200 --ber 1e-3
|
||||
```
|
||||
|
||||
### 3. Regular LDPC, rate 0.90 (`exp/`)
|
||||
|
||||
* What: regular LDPC, PEG construction, min-sum belief propagation.
|
||||
n=8192 bits, column weight 3, m=768 checks, row weight 32,
|
||||
k=7424 bits (928 B). Fixed seed, so the code is identical on every
|
||||
run and every server. Systematic encoding by Gauss-Jordan reduction
|
||||
of H to [I | P] (one-time, at codec creation, ~1.8 s init).
|
||||
* Measured (text.lz, 64 KiB, 200 trials): `ldpc-r90` recovers 1.00
|
||||
at BER 1e-3 and 0.97 at 3e-3, where `bch1k-t32` recovers 0.01 at
|
||||
3e-3 — the iterative decoder's cliff sits a decade higher in BER.
|
||||
Overhead 10.94%. Bursts kill it (16 B burst: 0.24); LDPC+interleave
|
||||
is the follow-up. `ldpc-r95` is weak (0.32 at 1e-3, fails at
|
||||
6 errors/block); irregular LDPC is the follow-up.
|
||||
* Speed: 3.34 MB/s enc, 0.91 MB/s dec — ~4x slower decode than
|
||||
`bch1k-t32`.
|
||||
* Use:
|
||||
```
|
||||
./bench --codec ldpc-r90 --blob corpora/text.lz \
|
||||
--size 65536 --trials 200 --ber 1e-3
|
||||
./ldpc_diag r90 40 50 # single-block error-count sweep
|
||||
```
|
||||
|
||||
### 4. Dictionary transform, code-only opt-in (`experiments/`)
|
||||
|
||||
* What: per-file word dictionary (top 4096 words by saving,
|
||||
transmitted in the header), words -> 3-byte codes, then lzip -6.
|
||||
Format: magic `DICT`, u32 orig_len, u16 ndict, entries (u8 len,
|
||||
bytes); 0xFF escape introduces a 2-byte code.
|
||||
* Measured (8 MiB corpora, lzip -6): code 9.19% vs plain lzip6 9.38%
|
||||
(-2.1% better — long repeated identifiers survive as codes better
|
||||
than as LZ matches). Everywhere else the dictionary costs more
|
||||
than it saves: text 3.58 vs 3.56 (+0.5% worse), bin 33.30 vs 32.61,
|
||||
mixed 17.65 vs 17.41, rand worse. Not a default; a code-only
|
||||
optional preprocessing stage at most.
|
||||
* End-to-end BCH check (`bchcheck`): dict+lzip code blob (770,519 B)
|
||||
BCH t=8, 8 flips -> 8 corrected, full pipeline recovers
|
||||
bit-identical; 32 flips -> decode FAIL (beyond t=8, honest failure).
|
||||
* Use (dict takes file paths, not stdin):
|
||||
```
|
||||
./dict c code.c code.dict && lzip -6 code.dict
|
||||
lzip -dc code.dict.lz > code.dict2 && ./dict d code.dict2 code.c.out
|
||||
```
|
||||
|
||||
### Supporting infrastructure: rANS core (`experiments/rans.[ch]`)
|
||||
|
||||
* What: the shared entropy stage for the prototypes — static
|
||||
per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
|
||||
RSS ~20 MB. Kept as reusable infrastructure, not as a standalone
|
||||
compressor: order-0 rANS alone scores text 64.40%, code 67.62%
|
||||
(no LZ stage), so it is a reject as a compressor and a keep as a
|
||||
core. Two real bugs fixed on the branch (renormalisation threshold;
|
||||
emitted stream can exceed n bytes, scratch is 2n+64).
|
||||
* Use: `./rans_tool c in out` / `./rans_tool d in out`.
|
||||
|
||||
## Rejects (measured, not carried over)
|
||||
|
||||
Only their numbers stay (in `exp/README.md`, `experiments/README.md`,
|
||||
`experiments/results/*.csv`); the code was removed in the integration
|
||||
cleanup commit.
|
||||
|
||||
| family | verdict | numbers |
|
||||
|---|---|---|
|
||||
| Polar SC (`polar-r90`) | dominated, rejected | 0.00 at BER 1e-3 at every design point; designing for p=1e-2 gives 0.00 at 1e-4; best (d4) 0.95 at 1e-4. Dec 0.58 MB/s, slowest of all. SCL list decoding is the follow-up that could rescue it. |
|
||||
| UEP (unequal error protection) | conditional, not integrated | Whole-file recovery dominated by the weak tier (0.00 at 1e-3). The 1-4 KiB prefix survives (1.00 at 1e-3, 1.00 at 256 B burst) — but only useful if lzply gains a salvage mode; today the entry SHA gates all-or-nothing extraction. |
|
||||
| LZ77 + rANS (`lzrans`) | rejected as a lzip replacement | lazy: text 6.26, code 13.52, bin 41.84, mixed 23.15; optimal parsing recovers only ~1-3% relative — the gap is LZMA's adaptive context entropy model, not parsing. |
|
||||
| BWT + MTF + rANS | rejected | text 6.35 (beats bzip2's 9.25), code 12.31, bin 42.76; loses to lzip everywhere; encode 0.05 MB/s (~3 min/8 MB), decode 5-6 MB/s, RSS ~200 MB. |
|
||||
| PPM order-2 + arithmetic | rejected | text 32.84, code 30.82, mixed 39.18; ~6 MB/s enc, ~4 MB/s dec. Nowhere near PPMd-class. |
|
||||
| rANS order-0 standalone | rejected as a compressor | text 64.40, code 67.62, bin 77.14 — no LZ stage. Core kept (above). |
|
||||
|
||||
## Baselines the winners were measured against
|
||||
|
||||
* As-shipped BCH (`bch-t32`): one 64 KiB blob = one BCH block
|
||||
(m=20, 80 parity bytes, 0.12% overhead, 32 correctable bits per
|
||||
64 KiB). Cliff between BER 1e-5 and 1e-4 (1.00 -> 0.01).
|
||||
* Pass 2 (hash-gated candidates) rescues nothing in practice:
|
||||
0/875 in the pass-2 matrix, 0/50 at every k in the targeted sweep.
|
||||
Its demonstrated value is the loud-failure guarantee: 0 silent
|
||||
miscorrections in 7813 checks. See `docs/BASELINE.md`.
|
||||
* lzip (the current lzply stage): text 3.44-3.56%, code 9.05-9.38%,
|
||||
bin 32.53-32.61%, mixed 17.17-17.41% at -9..-6. No prototype family
|
||||
beats lzip on ratio. See `experiments/README.md`.
|
||||
|
||||
## Verification on the integrated tree
|
||||
|
||||
* `make -j8` then `make test` runs the full suites (bch_test,
|
||||
rs_test, crc16_test, run_rs_tests.sh, run_tests.sh,
|
||||
run_deep_repair_tests.sh, run_hyper_tests.sh) plus
|
||||
`tests/run_integration_tests.sh`: clean round-trips for all three
|
||||
ECC codecs, intlv-d64 burst survival + uninterleaved control,
|
||||
bch1k BER survival + as-shipped control, LDPC BER survival,
|
||||
rANS round-trip, dict+lzip round-trip, bchcheck 8-flip recovery
|
||||
and 32-flip expected failure, LZPL v5 archive round-trip.
|
||||
* Cross-corpus check on the branches reproduced text.lz exactly on
|
||||
bin.lz and rand.lz for every codec and setting.
|
||||
|
||||
## Build
|
||||
|
||||
```
|
||||
make -j8 # main tools + lz_rs + deep repair
|
||||
make exp # exp/bench + ldpc_diag + pass2_diag
|
||||
make experiments # experiments/rans_tool + dict + bchcheck
|
||||
make test # full suites + integration smoke tests
|
||||
```
|
||||
|
||||
## Fresh numbers on the integrated tree (hot_newyork, 2026-12-02)
|
||||
|
||||
Re-measured after the merge with `bench-integration.sh` (best-of-3
|
||||
timings, load ~1.2-1.6). Data set: mixed dir 25,521,882 bytes (repo
|
||||
text + repo C sources + /bin/ls, /bin/cat, /usr/bin/lzip) + 1 MiB
|
||||
/dev/urandom. The lzply core is untouched by the integration, so the
|
||||
plain-lzply numbers below are the b27b345 numbers.
|
||||
|
||||
Plain lzply at b27b345:
|
||||
- `lzply -c -6` mixed: 7,060,165 bytes, 22.904 s compress / 1.594 s extract
|
||||
- `lzply -c -6 -e 0` mixed: 7,059,797 bytes (BCH adds 368 bytes here)
|
||||
- `lzply -c -6` rand1m: 1,048,750 bytes (stored, level 0), 0.577 s / 0.060 s
|
||||
|
||||
exp bench --speed, mixed.lz blob (308,207 bytes), 64 KiB windows:
|
||||
- bch-t32: enc 8.59 MB/s, dec 4.28 MB/s, overhead 0.12%
|
||||
- bch1k-t32: enc 3.72 MB/s, dec 1.93 MB/s, overhead 5.40%
|
||||
- intlv-d64-bch1k-t32: enc 3.77 MB/s, dec 1.72 MB/s, overhead 5.40%
|
||||
- ldpc-r90: enc 4.08 MB/s, dec 1.07 MB/s, overhead 10.94%, init 1.87 s
|
||||
|
||||
Recovery on the mixed blob (fresh, reproduces the branch matrices):
|
||||
- intlv-d64-bch1k-t32, 256 B burst: 1.000 (20 trials)
|
||||
- bch1k-t32, BER 1e-3: 1.000 (20 trials)
|
||||
- ldpc-r90, BER 1e-3: 1.000 (10 trials)
|
||||
|
||||
Dictionary transform on this corpus (repo C sources only, 786,430
|
||||
bytes): plain lzip6 120,409 vs dict+lzip6 123,662 (+2.7% worse) --
|
||||
the branch -2.1% win was on header-heavy code (8 MiB of /usr/include
|
||||
headers + repo sources). On text (1,004,068 bytes): plain 187,798 vs
|
||||
dict 191,045 (+1.7% worse). The code-only conditional stands, and it
|
||||
is corpus-dependent: headers win, plain C sources do not.
|
||||
|
||||
rANS order-0 on text (1,004,068 bytes): 614,658 bytes (61.2%),
|
||||
enc ~31 MB/s, dec ~42 MB/s.
|
||||
@@ -1,213 +0,0 @@
|
||||
# Deep repair — past the BCH limit t
|
||||
|
||||
`lzply_deep_repair` recovers archive entries whose bit errors exceed
|
||||
the BCH correction limit t, in escalating levels, reporting
|
||||
per-level timing ("time of arrival": how long each level took and
|
||||
at which level the repair landed). The CRC16 is the oracle: every
|
||||
beyond-t candidate is CRC-verified before acceptance, then
|
||||
decompressed and SHA-256-checked.
|
||||
|
||||
## The levels
|
||||
|
||||
- **L0 — standard decode to t.** The normal BCH (and RS, for LZRS)
|
||||
decode. If it succeeds, the entry is recovered at L0.
|
||||
- **L1 — Chase-1.** Single-bit trial flips: the suspect positions
|
||||
first, then an exhaustive scan of every codeword bit position.
|
||||
For each trial flip the syndrome is updated by XOR-ing the
|
||||
flipped bit's syndrome column, Berlekamp-Massey runs on the
|
||||
trial syndrome, and a candidate is kept only if the locator
|
||||
splits completely over GF(2^m) (a gcd test against x^(2^m)−x),
|
||||
the Chien search finds all its roots at in-range positions, and
|
||||
the corrected word has zero remainder. Recovering t+1 is a
|
||||
theorem, not luck: flipping any one true error leaves t errors,
|
||||
which BM corrects. Chase-1 can never recover t+2 (one flip plus
|
||||
at most t Chien corrections cannot span t+2 errors — also a
|
||||
theorem).
|
||||
- **L2 — Chase-2.** Two-bit trial flips: pairs within the suspect
|
||||
set, then pairs (first element, any position) where the first
|
||||
element ranges over a bounded list — the suspects, then ascending
|
||||
bit positions, at most 128 entries in total
|
||||
(`BCH_CHASE2_FIRST_MAX`). At most 128·nbits trials, plus a
|
||||
wall-clock deadline. The recovery rate scales with the list
|
||||
size: roughly 1 − (1 − (t+2)/nbits)^F for F first elements on a
|
||||
weight-(t+2) pattern.
|
||||
- **L3 — cross-block list decoding.** Two failing blocks varied at
|
||||
once from retained per-block candidate pools (at most 256 blob
|
||||
tries, `DEEP_MAX_BLOB_CANDS`). Lands when each of two blocks
|
||||
holds its true data in the pool but neither single-block
|
||||
variation passes the CRC.
|
||||
|
||||
## Why the suspect set does not help Chase-2 (much)
|
||||
|
||||
With hard-decision input there is no channel reliability, so
|
||||
"least-reliable bits" come from the decoder itself: the Chien
|
||||
roots of the failed decode, the residual-BM difference set, and
|
||||
their neighbours. For Chase-1 the suspects only order the scan
|
||||
(the exhaustive scan covers everything anyway). For Chase-2 the
|
||||
suspects head the first-element list — but they provably do NOT
|
||||
overlap the true errors for random patterns: the failed decode's
|
||||
root set and the true error set have the same syndrome, so they
|
||||
differ by a codeword of weight ≥ 2t+1, which forces zero overlap
|
||||
when the failed decode returns a full root set. A suspect is
|
||||
therefore no more likely than any other position to be a true
|
||||
error, and Chase-2's rate comes from the size of the
|
||||
first-element list (the positional prefix does the work), not
|
||||
from the suspects. The list is what buys the rate. (Measured:
|
||||
in `bch_test` phase 8 the suspect set was empty in 15 of 30
|
||||
trials — when the failed decode's locator has no in-range roots
|
||||
there is nothing to suspect — and Chase-2 still runs, on the
|
||||
positional prefix alone.)
|
||||
|
||||
## Bounds (all enforced)
|
||||
|
||||
| bound | value | where |
|
||||
|---|---|---|
|
||||
| chase1 trials | ≤ nbits (one per codeword bit) | `bch_chase1_block` |
|
||||
| chase2 trials | ≤ 128·nbits + 496 | `bch_chase2_block` |
|
||||
| candidates per chase call | ≤ 64 distinct blocks | `BCH_CHASE_MAX_CANDS` |
|
||||
| candidates retained per block (L3 pool) | ≤ 64 (2× `DEEP_MAX_BLOCK_CANDS`) | `deep_repair.h` |
|
||||
| L3 blob tries | ≤ 256 | `DEEP_MAX_BLOB_CANDS` |
|
||||
| retained pool memory | ≤ 128 MiB | `DEEP_MAX_POOL_BYTES` |
|
||||
| time budget | default 120 s per entry (`--time-budget`) | CLI |
|
||||
| max level | 0..3 (`-l`) | CLI |
|
||||
|
||||
A deadline stops a scan early; the stats report `partial=1` and
|
||||
how many trials ran, so a budget-limited run is honest about its
|
||||
coverage. The tool exits 0 when every entry recovered, 3 when
|
||||
any failed, 1 on usage errors, 2 on I/O errors.
|
||||
|
||||
## The oracle and the false-accept rate
|
||||
|
||||
Every candidate blob is CRC16-checked before decompression; only
|
||||
CRC-passing candidates go to decompress + SHA-256. Expected
|
||||
residual false-accept is ~2^-16 per candidate at the CRC stage
|
||||
(the SHA-256 stage then gates acceptance). Measured across the
|
||||
corruption matrix (see below): 1,162 candidates CRC-checked,
|
||||
1,024 rejected by CRC, 0 false accepts. The strongest stress is
|
||||
at small t: at t=4 there are hundreds of codewords within t+2 of
|
||||
a random word, so Chase-2 returns ~66 wrong-but-valid candidates
|
||||
per trial and the CRC rejects all of them; at t=8 there are
|
||||
almost none, so the chase returns few wrong candidates at all.
|
||||
(The far-past-t cases produce no codewords: the chase finds
|
||||
nothing to offer the CRC.)
|
||||
|
||||
## CLI
|
||||
|
||||
```
|
||||
lzply_deep_repair [-l max-level 0..3] [--time-budget seconds] [-v]
|
||||
[-o outdir] [--entry name] archive
|
||||
```
|
||||
|
||||
Per-entry output:
|
||||
|
||||
```
|
||||
path: RECOVERED at L1 in 0.070s (L0 0.000s, L1 0.069s, L2 0.000s, L3 0.000s) cands 1 crc-rejects 0 sha-rejects 0 bch-corrected 9
|
||||
```
|
||||
|
||||
or `path: FAILED (stage nocand) after 3.048s, cands 0 crc-rejects 0 ...`.
|
||||
`-v` adds per-level trial/split/codeword counts and the failed
|
||||
block count. The summary line gives per-level landing counts.
|
||||
Output files are written under `-o` (default `./repaired`),
|
||||
preserving stored paths; directory entries are recreated.
|
||||
Overwrites existing output files.
|
||||
|
||||
## Measured corruption matrix
|
||||
|
||||
`tests/run_deep_repair_tests.sh` (hot_newyork). Scattered errors
|
||||
are `corrupt_bits` over the whole blob; burst errors are
|
||||
`corrupt_run` (1 byte = 8 bit errors, 2 bytes = 16). All files
|
||||
use `-e 4` (t=8) unless noted. Recovery means the extracted bytes
|
||||
are bit-identical to the original; a RECOVERED entry whose bytes
|
||||
differ is a false accept and fails the suite.
|
||||
|
||||
<!-- MATRIX TABLE: filled in from the suite run -->
|
||||
|
||||
| cell | n | recovered | level | mean time | mean cands |
|
||||
|---|---|---|---|---|---|
|
||||
| r512, -e 4 (t=8), scatter 0 | 10 | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, scatter 4 | 10 | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, scatter 8 (= t) | 10 | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, scatter 9 (= t+1) | 10 | 10 | L1 | 0.04 s | 1 |
|
||||
| r512, -e 4, scatter 10 (= t+2) | 10 | 3 | L2 | 4.37 s | 0 |
|
||||
| r512, -e 4, scatter 11 | 10 | 0 | — | 4.38 s | 0 |
|
||||
| r512, -e 4, scatter 12 | 10 | 0 | — | 4.38 s | 0 |
|
||||
| r512, -e 4, burst 1 byte (8 bits) | 3 | 3 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, burst 2 bytes (16 bits) | 3 | 0 | — | 4.34 s | 0 |
|
||||
| r512, -e 3 (t=4), scatter 0/2/4 | 10 each | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 3, scatter 5 (= t+1) | 10 | 10 | L1 | 0.04 s | 3 |
|
||||
| r512, -e 3, scatter 6/7/8 | 5 each | 0 | — | 1.0–1.3 s | 66 |
|
||||
| r2048, -e 4, scatter 0/8 | 5 each | 5 | L0 | 0.00 s | 1 |
|
||||
| r2048, -e 4, scatter 9 (= t+1) | 5 | 5 | L1 | 0.17 s | 1 |
|
||||
| r2048, -e 4, scatter 10 (= t+2) | 5 | 0 | — | 20.75 s | 0 |
|
||||
| text 2 KiB, -e 4, scatter 0/8 | 5 each | 5 | L0 | 0.00 s | 1 |
|
||||
| text 2 KiB, -e 4, scatter 9 (= t+1) | 5 | 5 | L1 | 0.04 s | 1 |
|
||||
| big600, -e 4, scatter 8 | 2 | 2 | L0 | 0.66 s | 1 |
|
||||
| big600 pinned poly 001a, 9 in block 1 | 2 | 2 | L1 | 0.13 s | 1 |
|
||||
| big600 pinned poly 001a, 9+9 in blocks 1+2 | 2 | 2 | L3 | 16.67 s | 8 |
|
||||
| lz_rs -r 0, r512, scatter 9 | 3 | 3 | L1 | 0.04 s | 1 |
|
||||
| lz_rs -r 2, r512, scatter 9 | 3 | 3 | L0 | 0.00 s | 1 |
|
||||
|
||||
False-accept measurement (same run): t+2 cases 10/20 recovered at
|
||||
L2 with 10 candidates CRC-checked and 0 accepts; 24- and
|
||||
40-error cases 0/10 with 1 candidate CRC-checked (rejected) and
|
||||
0 accepts. **Matrix-wide: 1,162 candidates CRC-checked, 1,024
|
||||
rejected by CRC, 0 false accepts.** The dedicated false-accept
|
||||
cells are weak at t=8 (almost no codewords within t+2 of a random
|
||||
word, so the chase returns few wrong candidates); the strong
|
||||
evidence is the -e 3 (t=4) t+2 cells, where Chase-2 returns ~66
|
||||
wrong-but-valid candidates per trial and the CRC rejects all
|
||||
~992 of them.
|
||||
|
||||
## Limits, measured honestly
|
||||
|
||||
- **Chase scans are O(nbits) trials.** On m=22 blocks the trial
|
||||
rate is ~8,900/s (the GF(2^22) log/exp tables are 16 MiB each
|
||||
and stop fitting in cache; the multiply dispatches to the
|
||||
shift-and-xor path at m ≥ 17, which is ~3.5× faster than the
|
||||
cache-missing table lookup and arithmetically identical —
|
||||
`bch_test` 7,975 checks still pass). A full Chase-1 scan of a
|
||||
524 KiB block (4,194,296 trials) takes **471.9 s** (measured,
|
||||
probe5: RECOVERED at L1 in 471.918 s, trials 4,194,296,
|
||||
split 126, codewords 126). The tool scans fully before trying
|
||||
candidates (the chase layer has no oracle), so the landing time
|
||||
is the full-scan time, not the time to the lowest true error.
|
||||
At the default 120 s budget a beyond-t repair of a 524 KiB
|
||||
block reports partial coverage and does not land. Small blocks
|
||||
are fast: a 512-byte block scans in ~0.07 s.
|
||||
- **L2's rate collapses on large blocks.** The recovery
|
||||
probability is roughly 1 − (1 − (t+2)/nbits)^128: ~26% on a
|
||||
512-byte block (measured 3/10 at t+2), ~7.5% on a 2 KiB block
|
||||
(measured 0/5), ~0.03% on a 524 KiB block. L2 is a small-block
|
||||
tool.
|
||||
- **L3 needs per-block candidates.** It can only combine what L1
|
||||
and L2 retained in the pools. On pinned small blocks it lands
|
||||
(measured: 9+9 errors in two blocks recovered at L3 in 2/2
|
||||
trials, mean 16.67 s — the L2 phase dominates at 17.7 s, the L3
|
||||
combine itself is 0.014 s); on large blocks the pools stay empty
|
||||
because L1/L2 cannot finish a scan in budget.
|
||||
- **Pass-2 (the two-pass repair in `bch.c`) recovers 0/100 at
|
||||
t+1 and t+2 on 4 KiB blocks** (measured in `bch_test` phase 6):
|
||||
for random patterns the failed decode's roots do not overlap
|
||||
the true errors, so the residual step finds nothing. Chase-1
|
||||
is what actually recovers t+1. (Pass-2 still helps when the
|
||||
failed decode happens to overlap, e.g. clustered errors.)
|
||||
|
||||
## Bugs found by measurement (fixed)
|
||||
|
||||
1. **The trial flip was not applied to the reconstructed word.**
|
||||
`chase_trial` flipped only the Chien roots into the work copy,
|
||||
not the trial flip itself — so a good trial reconstructed the
|
||||
wrong word and failed the remainder check. Chase-1 recovered
|
||||
0/20 at t+1 before the fix, 20/20 after. (The trial flips are
|
||||
part of the correction, not just a syndrome tweak.)
|
||||
2. **L1 pooled candidates before trying them.** The pool cap
|
||||
(16) truncated the candidate list, and the genuine candidate
|
||||
can arrive late in scan order (wrong-but-valid codewords
|
||||
accumulate at ~1 per 32K trials, so on a 4M-bit block the
|
||||
genuine candidate can be the 20th+ one returned). A 600 KiB
|
||||
file with 9 errors in one block failed at a 60 s budget before
|
||||
the fix; after the fix L1 tries Chase candidates directly in
|
||||
scan order (as L2 already did) and pools afterwards for L3 —
|
||||
it recovers at L1 in 471.9 s. The pool cap was also raised
|
||||
(`DEEP_MAX_BLOCK_CANDS` 8 → 32) so L3 retention keeps late
|
||||
genuine candidates.
|
||||
@@ -1,242 +0,0 @@
|
||||
# LZRS v1 — lzip + BCH + Reed-Solomon archives
|
||||
|
||||
`lz_rs` is `lzply` plus a Reed-Solomon layer: the same archive
|
||||
pipeline, the same modes (`-c -d -l -t -a -i -tr`, selectors, date
|
||||
filters), but the LZRS v1 format (magic `LZRS`) and one more layer
|
||||
of error correction. The BCH layer is unchanged (same 82
|
||||
polynomials, same `-e` levels, same two-pass hash-gated repair);
|
||||
RS is layered on the outside of it.
|
||||
|
||||
## Why two layers
|
||||
|
||||
BCH corrects scattered bit errors cheaply: for the same
|
||||
correction power it needs 39–42% less parity than Reed-Solomon
|
||||
(see the BCH study in the README). But BCH is a *bit* code — one
|
||||
bad byte with 8 flipped bits costs 8 of its t, and a burst that
|
||||
wipes a run of bytes costs far more. Reed-Solomon is a *symbol*
|
||||
code: one bad byte costs 1 of its t no matter how many bits in
|
||||
that byte flipped, so a burst of N bad bytes costs N. RS is the
|
||||
right tool for byte damage and bursts; BCH stays the right tool
|
||||
for scattered bit rot. Stacked, the archive survives both.
|
||||
|
||||
## Pipeline
|
||||
|
||||
Per entry, on write:
|
||||
|
||||
```
|
||||
raw bytes -> lzip compress (or store, level 0) -> BCH encode -> RS encode
|
||||
```
|
||||
|
||||
On read, the layers run in reverse:
|
||||
|
||||
```
|
||||
RS decode -> BCH decode (two-pass, hash-gated) -> lzip decompress -> SHA-256 check
|
||||
```
|
||||
|
||||
`blob_size` in the header is the compressed stream length before
|
||||
BCH and RS parity was added. Every layer length is reconstructible
|
||||
from the header alone: the BCH length from `blob_size` + the poly
|
||||
id, the RS length from the BCH length + the parity. A truncated or
|
||||
mis-sized entry fails the length check before any decoding.
|
||||
|
||||
The SHA-256 check at the end is the oracle for the whole stack:
|
||||
no data is ever returned unless it hashes correctly. A
|
||||
bounded-distance decoder can miscorrect when damage exceeds the
|
||||
level limit, and the hash is what catches it — the same guarantee
|
||||
lzply makes for BCH alone.
|
||||
|
||||
## RS parameters (`rs.c`, `rs.h`)
|
||||
|
||||
* Code: RS(255, 255-p) over GF(2^8), systematic (data first,
|
||||
parity after), first byte = highest-degree coefficient.
|
||||
* Field: primitive polynomial `0x11D`, primitive element
|
||||
alpha = 2, first consecutive root fcr = 0, so the generator is
|
||||
`g(x) = prod_{i=0}^{p-1} (x - alpha^i)`.
|
||||
* Block: 255 symbols. A block corrects up to `p/2` symbol (byte)
|
||||
errors.
|
||||
* Shortening: the last block of an entry holds fewer than
|
||||
`k = 255-p` data bytes. It is encoded as if zero-padded to `k`
|
||||
bytes, but only the data bytes present plus the `p` parity bytes
|
||||
are stored. The decoder reconstructs the zero pad (those symbols
|
||||
were never stored, so they cannot be corrupt) and, after
|
||||
correction, checks the pad is still zero — a miscorrection that
|
||||
flips a pad symbol is rejected outright.
|
||||
* Decode: syndromes → Berlekamp-Massey (error-locator polynomial)
|
||||
→ Chien search (error positions) → Forney (error magnitudes) →
|
||||
re-check the syndromes. Anything that does not come back clean
|
||||
is a loud failure, never a silent wrong answer at this layer.
|
||||
|
||||
## The `-r` levels
|
||||
|
||||
| level | parity symbols per 255-byte block | corrects per block | overhead on incompressible data |
|
||||
|-------|-----------------------------------|--------------------|----------------------------------|
|
||||
| 0 | 0 (no RS) | 0 | 0% |
|
||||
| 1 | 8 | 4 byte errors | ~3.2% |
|
||||
| 2 | 16 | 8 byte errors | ~6.7% |
|
||||
| 3 | 24 | 12 byte errors | ~10.4% |
|
||||
| 4 | 32 | 16 byte errors | ~14.3% |
|
||||
|
||||
Default is `-r 2` (16 parity symbols, 8 correctable byte errors
|
||||
per block). `-r 0` behaves like plain lzply: the stored bytes are
|
||||
byte-identical to what `lzply -e 0` writes for the same input
|
||||
(verified by the test suite — only the headers differ).
|
||||
|
||||
## Format (LZRS v1; all integers little-endian)
|
||||
|
||||
```
|
||||
global header (16 bytes):
|
||||
magic "LZRS", version u8 (=1), flags u8, entry_count u32, reserved u64
|
||||
entries, each:
|
||||
u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
u32 mode, u64 mtime, u16 bch_poly_id, u16 crc16, u32 header_crc32,
|
||||
path[path_len], data[stored_size]
|
||||
end marker: u16 path_len == 0
|
||||
```
|
||||
|
||||
The entry header is 82 bytes. `header_crc32` covers the 78 bytes
|
||||
before it. Level is the lzip level (1..9) of the blob, or 0 for a
|
||||
stored (uncompressed) entry, exactly as in lzply v4. Flags: bit 1
|
||||
= directory, bit 2 = BCH mode (same bits as v4; bit 0 is unused).
|
||||
`rs_level` is the RS level (0..4). `bch_poly_id` is the BCH
|
||||
polynomial id (0 when the entry has no BCH layer); it needed its
|
||||
own field because `rs_level` no longer carries the low byte of
|
||||
the poly id the way v4 does.
|
||||
|
||||
There is no legacy support: LZRS v1 is the only LZRS format.
|
||||
`lz_rs` rejects lzply v4 archives (`LZPL` magic) outright, and
|
||||
`lzply` rejects `.lzrs` archives (`LZRS` magic) outright — the
|
||||
test suite checks both directions. The `LZRS` magic is the same
|
||||
four bytes the original unreleased v1 Reed-Solomon format used
|
||||
(the README notes it as an old rejected magic); no archive from
|
||||
that v1 is known to exist, and one would fail the entry-header
|
||||
CRC here in any case, since the v1 entry layout differs from the
|
||||
82-byte layout above — it is rejected, never misread.
|
||||
|
||||
## CRC16 (implemented; the deep-repair oracle)
|
||||
|
||||
The `crc16` field in the entry header is CRC-16/CCITT-FALSE
|
||||
(polynomial 0x1021, init 0xFFFF, no reflection, xorout 0x0000;
|
||||
check value CRC16("123456789") == 0x29B1) of the **blob** — the
|
||||
compressed stream before BCH/RS parity was added (for a stored
|
||||
entry the blob is the raw bytes; for a directory entry the blob is
|
||||
empty, so crc16 == 0xFFFF). Writers compute and store it; readers
|
||||
verify it after error-correction decoding and before
|
||||
decompression. A mismatch is a clean failure, never a misdecode:
|
||||
the SHA-256 check remains the final oracle.
|
||||
|
||||
A stored crc16 of 0x0000 with a computed value that differs means
|
||||
the archive predates the CRC16 migration (old writers wrote 0):
|
||||
it is rejected with a message telling the user to re-create it.
|
||||
(An old archive whose blob CRC happens to be 0x0000, probability
|
||||
2^-16, would pass the CRC gate — but the SHA-256 check still gates
|
||||
the data, so it cannot misdecode.)
|
||||
|
||||
The CRC16 is the fast oracle for deep repair
|
||||
(`docs/deep-repair.md`): candidate blobs are CRC-checked before
|
||||
the expensive decompress + SHA-256 step, so most wrong candidates
|
||||
are rejected cheaply. Expected residual false-accept is ~2^-16
|
||||
per candidate at the CRC stage (the SHA-256 stage then gates
|
||||
acceptance). Measured: 1,162 candidates CRC-checked across the
|
||||
deep-repair corruption matrix, 1,024 rejected by CRC, 0 false
|
||||
accepts (see `tests/run_deep_repair_tests.sh`, matrix-results.txt).
|
||||
|
||||
## Usage
|
||||
|
||||
`lz_rs` takes the same arguments as `lzply`, plus `-r`:
|
||||
|
||||
```
|
||||
lz_rs -c -r 2 photos/ photos.lzrs # default RS level
|
||||
lz_rs -c -r 4 -e 5 -9 docs/ backup.lzrs
|
||||
lz_rs -c -r 0 docs/ no-rs.lzrs # no RS parity, like plain lzply
|
||||
lz_rs -c -r2 file.txt # attached form also works
|
||||
lz_rs -c --rs-level 3 file.txt # long form
|
||||
lz_rs -d backup.lzrs out/ # extract (RS+BCH repair automatic)
|
||||
lz_rs -t backup.lzrs # test (decode and verify)
|
||||
lz_rs -i backup.lzrs # inspect: shows "BCH 001a r2"
|
||||
lz_rs -l backup.lzrs # list
|
||||
lz_rs -tr backup.lzrs # tree
|
||||
lz_rs -a backup.lzrs more/ # append (new entries use the same -r)
|
||||
```
|
||||
|
||||
Exit codes are the same as lzply: 0 ok, 1 usage, 2 I/O error,
|
||||
3 corrupt/unrecoverable. On extract/test, a repaired entry prints
|
||||
what was fixed, e.g. `file OK (RS corrected 8 symbols)` or
|
||||
`file OK (RS corrected 3 symbols, BCH corrected 5 bits)`.
|
||||
|
||||
## Benchmarks (measured on hot_newyork, 8 cores)
|
||||
|
||||
testdata/mixed: 2,387,757 bytes in, 13 entries, default `-e 4 -6`:
|
||||
|
||||
| -r | archive bytes | compress | extract |
|
||||
|----|--------------:|---------:|--------:|
|
||||
| 0 | 1,065,039 | 772 ms | 92 ms |
|
||||
| 1 | 1,099,551 | 754 ms | 143 ms |
|
||||
| 2 | 1,136,367 | 811 ms | 191 ms |
|
||||
| 3 | 1,175,727 | 819 ms | 252 ms |
|
||||
| 4 | 1,217,903 | 872 ms | 307 ms |
|
||||
|
||||
random.bin: 1,048,576 bytes of incompressible data:
|
||||
|
||||
| -r | archive bytes | compress | test |
|
||||
|----|--------------:|---------:|-----:|
|
||||
| 0 | 1,048,752 | 515 ms | 49 ms |
|
||||
| 1 | 1,082,720 | 555 ms | 106 ms |
|
||||
| 2 | 1,118,960 | 512 ms | 158 ms |
|
||||
| 3 | 1,157,712 | 565 ms | 218 ms |
|
||||
| 4 | 1,199,248 | 545 ms | 271 ms |
|
||||
|
||||
RS overhead on incompressible data is +33,968 / +36,240 / +38,752 /
|
||||
+41,536 bytes per level step — about 3.2–3.9% of the data per step.
|
||||
Compress time is flat across levels (lzip + BCH dominate); decode
|
||||
time grows about 50 ms per level per MiB (Berlekamp-Massey + Chien
|
||||
search per block). Small compressible files cost almost nothing:
|
||||
text.txt (218,800 bytes) archives to 644 bytes at `-r 0` and 740
|
||||
at `-r 4` (+24 bytes per level).
|
||||
|
||||
## Tests
|
||||
|
||||
* `rs_test` (unit): 6,243 checks, 0 failures. Covers the
|
||||
level→parity mapping, encoded lengths, clean round-trips at
|
||||
every parity for 15 buffer lengths (including shortened last
|
||||
blocks and empty input), determinism, an independent
|
||||
re-implementation cross-check of the encoder (own GF tables,
|
||||
own generator build, own polynomial division — 200 random blocks
|
||||
per parity), a syndrome-zero check on every encoded block, and
|
||||
corruption recovery: random symbol errors and burst errors up
|
||||
to t per block must decode back to the exact original, while
|
||||
t+1 errors in one block must never decode back to the original.
|
||||
Parity-byte-only errors and shortened-last-block errors are
|
||||
covered explicitly.
|
||||
* `tests/run_rs_tests.sh` (shell, wired into `make test`): 59
|
||||
checks, 0 failures. Covers round-trips at every `-r` level,
|
||||
`-e 0` / `-e 7` / `-0` combinations, determinism, `-r2` and
|
||||
`--rs-level` forms, `-r 5` rejection, `-l` / `-tr` / `-i`,
|
||||
selectors, empty and one-byte files, append + duplicate
|
||||
replacement, byte-identical stored data for `-r 0` vs
|
||||
`lzply -e 0`, and the corruption matrix on a 1 MiB random file
|
||||
at every level: t scattered byte errors recovered, t errors in
|
||||
one block recovered, burst of t recovered, burst of 2t over a
|
||||
block boundary recovered, t+1 in one block fails with exit 3,
|
||||
burst of t+1 fails with exit 3, 8 scattered bit errors
|
||||
recovered (BCH layer under RS), `-i` still works on corrupted
|
||||
data. Also `-e 0 -r 2` (RS alone) recovers 8 and fails 9, both
|
||||
formats reject each other, and a truncated archive fails.
|
||||
|
||||
## Notes and differences from lzply
|
||||
|
||||
* `lz_rs.c` is derived from `lzply.c`: same modes, same
|
||||
helpers, same append/selectors/date-filter logic, with the
|
||||
format calls swapped (82-byte LZRS headers, `lzrs_entry_encode`
|
||||
/ `lzrs_entry_decode`, `-r` option). The shared core
|
||||
(`lzply_lib.c`, `bch.c`, `sha256.c`) is untouched — no
|
||||
regression risk to the existing tools. `lzply_mount`,
|
||||
`lzply_stat`, `lzply_heal`, `lzply_check` and `lzply_refresh`
|
||||
do not read LZRS archives; that is out of scope for this job.
|
||||
* Temp files created during append still use the shared
|
||||
`.lzply-tmp-XXXXXX` name from `lzply_lib.c` (cosmetic only).
|
||||
* Directory entries carry `rs_level` 0 in the header (they hold
|
||||
no data), so `-i` shows them as `RS r0`.
|
||||
* The RS codec is self-contained (`rs.c`, no external library):
|
||||
encoder and decoder share the same generator, so no outside RS
|
||||
implementation is needed or assumed.
|
||||
@@ -1,6 +0,0 @@
|
||||
bench
|
||||
ldpc_diag
|
||||
pass2_diag
|
||||
*.o
|
||||
corpora/
|
||||
results/
|
||||
@@ -1,26 +0,0 @@
|
||||
# exp/Makefile - build the ECC experiments harness (bench).
|
||||
# Links the real lzply BCH + SHA-256 from the repo root.
|
||||
CC ?= gcc
|
||||
CFLAGS ?= -O2 -Wall -Wextra -march=native
|
||||
CPPFLAGS ?= -I. -I..
|
||||
|
||||
SRCS = bench.c bch_wrap.c interleave.c ldpc.c \
|
||||
../bch.c ../sha256.c
|
||||
OBJS = $(SRCS:.c=.o)
|
||||
|
||||
bench: $(OBJS)
|
||||
$(CC) $(CFLAGS) -o $@ $(OBJS) -lm
|
||||
|
||||
ldpc_diag: ldpc_diag.c ldpc.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ ldpc_diag.c ldpc.c -lm
|
||||
|
||||
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f bench ldpc_diag pass2_diag $(OBJS)
|
||||
|
||||
.PHONY: clean
|
||||
-206
@@ -1,206 +0,0 @@
|
||||
# lzply ECC experiments (branch `experiments/ecc`)
|
||||
|
||||
> Integrated onto current main (`experiments/integration`, LZPL v5):
|
||||
> the winners here are interleaving d64, small-block BCH 1 KiB, and
|
||||
> LDPC r90. Polar and UEP were measured, rejected, and their code was
|
||||
> NOT carried over — see `docs/INTEGRATION.md`.
|
||||
|
||||
Open-ended error-correction research on top of lzply's BCH baseline.
|
||||
Each family implements `ecc_iface.h` (whole-blob encode/decode) and is
|
||||
measured by `bench.c` on the same corpora, same corruption matrix, same
|
||||
success criterion (exact recovery, memcmp + SHA-256).
|
||||
|
||||
## How to run
|
||||
|
||||
```
|
||||
./bench --codec bch-t32 --blob corpora/text.lz --size 65536 \
|
||||
--trials 200 --ber 1e-3 --nopass2 --out results/x.csv
|
||||
./bench --codec ldpc-r90 --blob corpora/text.lz --burst 256,1 --trials 200
|
||||
./bench --codec bch-t32 --blob corpora/text.lz --speed
|
||||
./ldpc_diag r90 40 50 # single-block error-count sweep
|
||||
./uep_diag uep-c1024-h32-l8 corpora/text.lz 65536 50 --ber 1e-3
|
||||
```
|
||||
|
||||
Modes: `--ber X` (independent bit flips), `--burst LEN,COUNT`
|
||||
(COUNT randomized-byte bursts of LEN bytes), `--clean`, `--speed`.
|
||||
`--nopass2` skips the (slow) second-chance recovery hook so the matrix
|
||||
stays fast; `run_pass2.sh` measures rescue rates separately.
|
||||
`run_matrix.sh <corpus> <size> <trials> <out.csv> <codec...>` runs the
|
||||
full matrix (5 BERs + 5 burst settings + clean), parallel over cores.
|
||||
|
||||
Corpora (`mkcorpora.sh`, generated, not committed): `text.lz` /
|
||||
`bin.lz` / `rand.lz` — lzip -9 of 4 MiB text, binaries, seeded random
|
||||
bytes (the compressed blob is what lzply protects); `*.raw` — the
|
||||
stored-entry case. Default window is 64 KiB.
|
||||
|
||||
## Families
|
||||
|
||||
| codec | what it is |
|
||||
|---|---|
|
||||
| `bch-t{2,4,8,16,32}` | Baseline: BCH exactly as lzply ships it (auto-pick poly for the whole blob; pass 2 via `recover_verified`). |
|
||||
| `bch1k-t{8,16,32}` | Same BCH, forced m=13 blocks (971 data bytes/block) — the "spend real redundancy" point. |
|
||||
| `intlv-d{D}-bch1k-t{T}` | Byte interleaver (depth D) over bch1k-t{T}. Zero extra parity; bursts spread across blocks. Groups merge the short tail (see below). |
|
||||
| `ldpc-r{90,95}` | Regular LDPC, PEG construction, min-sum belief propagation. |
|
||||
| `polar-r{90,95}[-d{2,3,4}]` | Polar code, SC decoding. `-dN` is the design crossover 1e-N (default d2 = 1e-2). The design point matters enormously (see below). |
|
||||
| `uep-c{C}-h{H}-l{L}` | Unequal error protection: first C bytes at BCH t=H, rest at t=L (small blocks). |
|
||||
|
||||
## Results (text.lz, 64 KiB windows, 200 trials/setting, hot_newyork)
|
||||
|
||||
Recovery rate = fraction of trials exactly recovered. Overhead is
|
||||
measured (stored/data - 1). Pass-2 rescue rates are in
|
||||
results/pass2-text.csv (separate, 25 trials/setting).
|
||||
|
||||
### Baseline: what lzply ships is nearly unprotected
|
||||
|
||||
| codec | ovh | BER 1e-5 | 1e-4 | 1e-3 | 3e-3 | 1e-2 | burst 256 B |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| bch-t2 | 0.01% | 0.11 | 0 | 0 | 0 | 0 | 0 |
|
||||
| bch-t8 | 0.03% | 0.88 | 0 | 0 | 0 | 0 | 0 |
|
||||
| bch-t16 | 0.06% | 1.00 | 0 | 0 | 0 | 0 | 0 |
|
||||
| bch-t32 | 0.12% | 1.00 | 0.01 | 0 | 0 | 0 | 0 |
|
||||
|
||||
One 64 KiB blob is a single BCH block (m=20, 80 parity bytes), so
|
||||
t=32 corrects 32 bit errors per 64 KiB. At BER 1e-4 the blob already
|
||||
carries ~52 errors: the cliff is between 1e-5 and 1e-4.
|
||||
|
||||
Pass 2 (hash-gated candidates) rescues nothing in practice:
|
||||
the repo's own bch_test reports t+1 recovered 0/100 and t+2
|
||||
recovered 0/100; this harness's pass2 matrix (35 rows, 875 trials,
|
||||
all BCH codecs) shows rescued=0 in every setting, and a targeted
|
||||
sweep (pass2_diag, m=13 t=16, k=t+1..t+8) rescues 0/50 at every k. Its mechanism (residual-BM)
|
||||
addresses pass-1 miscorrection, which essentially never happens
|
||||
for random errors (pass 1 fails rather than miscorrecting), and
|
||||
the flip-and-redecode fallback does not reach the true codeword.
|
||||
Its demonstrated value is the loud-failure guarantee: 0 silent
|
||||
miscorrections in 7813 checks. The matrix numbers above are
|
||||
therefore the true lzply numbers with or without pass 2.
|
||||
|
||||
### Spending redundancy: small-block BCH
|
||||
|
||||
| codec | ovh | BER 1e-4 | 1e-3 | 3e-3 |
|
||||
|---|---|---|---|---|
|
||||
| bch1k-t8 | 1.29% | 1.00 | 0 | 0 |
|
||||
| bch1k-t16 | 2.62% | 1.00 | 0.73 | 0 |
|
||||
| bch1k-t32 | 5.40% | 1.00 | 1.00 | 0.01 |
|
||||
|
||||
Same code, 1 KiB blocks: t=32 buys survival to BER 1e-3 at 5.4%
|
||||
overhead. Bursts still kill it (256 B burst: 0.00 at every t).
|
||||
|
||||
### Interleaving: zero-overhead burst protection (WINNER)
|
||||
|
||||
Byte interleave over bch1k-t32, 5.40% overhead (unchanged):
|
||||
|
||||
| codec | burst 16 B | 64 B | 256 B | 1024 B | 4x64 B |
|
||||
|---|---|---|---|---|---|
|
||||
| bch1k-t32 (no intlv) | 0 | 0 | 0 | 0 | 0 |
|
||||
| intlv-d16-t32 | 1.00 | 1.00 | 0 | 0 | 0.10 |
|
||||
| intlv-d32-t32 | 1.00 | 1.00 | 0 | 0 | 0.80 |
|
||||
| intlv-d64-t32 | 1.00 | 1.00 | 1.00 | 0 | 1.00 |
|
||||
|
||||
Random-error performance is unchanged by construction (same BCH
|
||||
underneath). Even at 1.29% overhead, intlv-d64-bch1k-t8 survives
|
||||
64 B bursts at 1.00. Gotcha fixed en route: a short tail group
|
||||
(4 blocks of 68) was the weak point and measured 0.94 on 64 B
|
||||
bursts; groups now merge the tail.
|
||||
|
||||
### LDPC: the random-error winner (WINNER at ~11% overhead)
|
||||
|
||||
| codec | ovh | BER 1e-3 | 3e-3 | 1e-2 | burst 16 B |
|
||||
|---|---|---|---|---|---|
|
||||
| ldpc-r90 | 10.94% | 1.00 | 0.97 | 0 | 0.24 |
|
||||
| ldpc-r95 | 6.25% | 0.32 | 0 | 0 | 0 |
|
||||
|
||||
At BER 3e-3, ldpc-r90 recovers 0.97 where bch1k-t32 recovers 0.01
|
||||
— the iterative decoder's cliff sits a decade higher in BER. But
|
||||
bursts kill it (a 16 B burst is ~64 errors in one 1 KiB block),
|
||||
and r95 is weak: the regular (3,64) code starts failing at 6
|
||||
errors/block (ldpc_diag). Irregular LDPC would be the follow-up;
|
||||
LDPC+interleave would fix bursts.
|
||||
|
||||
### Polar SC: dominated, rejected (honest negative)
|
||||
|
||||
Designing for p=1e-2 gives 0.00 at BER 1e-4; designing for the
|
||||
operating point (d3/d4) gives 0.90/0.95 at 1e-4 — but every variant
|
||||
is 0.00 at BER 1e-3. SC at N=4096/R=0.9 is far weaker than
|
||||
bch1k-t32 (1.00 at 1e-3, half the overhead) and ldpc-r90 (1.00 at
|
||||
1e-3, same overhead). Two real bugs were fixed en route (SC partial
|
||||
sums overwrote the leaf decisions; see polar.c). SCL list decoding
|
||||
is the follow-up that could rescue polar; SC as measured is a reject.
|
||||
|
||||
### UEP: graceful degradation, conditional
|
||||
|
||||
Exact recovery is dominated by the weak tier (uep-c1024-h32-l8 at
|
||||
1e-3: 0.00, same as uniform bch1k-t8). The prefix tells another
|
||||
story (uep_diag, 50 trials):
|
||||
|
||||
| codec | BER 1e-3 whole | BER 1e-3 prefix | burst 256 B prefix |
|
||||
|---|---|---|---|
|
||||
| uep-c1024-h32-l8 | 0.00 | 1.00 | 1.00 |
|
||||
| uep-c4096-h32-l8 | 0.00 | 1.00 | 0.94 |
|
||||
|
||||
The first 1-4 KiB (lzip header + stream start) survives when the
|
||||
file is lost. Only useful if lzply gains a salvage mode; today the
|
||||
entry SHA gates all-or-nothing extraction.
|
||||
|
||||
## Speed and memory (isolated, sequential, 64 KiB blob, clean)
|
||||
|
||||
`--speed` mode, 5 reps each. RSS is the bench process peak (harness
|
||||
+ buffers ~6.5 MB); the codec delta is what matters.
|
||||
|
||||
| codec | enc MB/s | dec MB/s | RSS KB | ovh |
|
||||
|---|---|---|---|---|
|
||||
| bch-t32 | 6.46 | 3.44 | 6564 | 0.12% |
|
||||
| bch1k-t8 | 9.98 | 5.87 | 6560 | 1.29% |
|
||||
| bch1k-t16 | 5.39 | 3.14 | 6492 | 2.62% |
|
||||
| bch1k-t32 | 2.97 | 1.55 | 6652 | 5.40% |
|
||||
| intlv-d64-t32 | 3.39 | 1.73 | 6720 | 5.40% |
|
||||
| intlv-d64-t8 | 11.11 | 5.80 | 6572 | 1.29% |
|
||||
| ldpc-r90 | 3.34 | 0.91 | 7776 | 10.94% |
|
||||
| ldpc-r95 | 5.18 | 1.16 | 7652 | 6.25% |
|
||||
| polar-r90-d4 | 4.82 | 0.58 | 7252 | 11.72% |
|
||||
| uep-c1024-h32-l8 | 9.96 | 4.80 | 6612 | 1.43% |
|
||||
|
||||
Interleaving costs nothing measurable (same speed and memory as
|
||||
the BCH underneath; it is a permutation). LDPC pays a one-time
|
||||
~1.8 s init (PEG + Gauss-Jordan) and decodes ~4x slower than
|
||||
bch1k-t32; polar decodes slowest of all (0.58 MB/s). Failed BCH
|
||||
decodes are far slower than clean ones (pass 2 dominates; matrix
|
||||
rows for failed whole-blob blocks read 0.02-0.10 MB/s).
|
||||
|
||||
## Generalization
|
||||
|
||||
Cross-corpus check (bin.lz, rand.lz, 100 trials/setting, headline
|
||||
codecs, BER 1e-4/1e-3 + 256 B burst + clean) reproduces text.lz
|
||||
exactly for every codec and setting: bch1k-t32 1.00/1.00/0.00,
|
||||
intlv-d64-t32 1.00/1.00/1.00, ldpc-r90 1.00/1.00/0.00,
|
||||
polar-r90-d4 0.94/0.00/0.00, uep-c1024 1.00/0.00/0.00. Clean
|
||||
round-trips are bit-identical everywhere (all clean rows 1.00).
|
||||
|
||||
## Test totals
|
||||
|
||||
- BCH matrix (text.lz): 143 rows x 200 trials = 28,600 trials
|
||||
- LDPC matrix: 22 rows x 200 = 4,400
|
||||
- Polar matrix: 33 rows x 200 = 6,600
|
||||
- UEP matrix: 33 rows x 200 = 6,600
|
||||
- Pass-2 matrix: 35 rows x 25 = 875 (rescued 0)
|
||||
- Cross-corpus: 48 rows x 100 = 4,800
|
||||
- Diagnostics: ldpc_diag single-block sweeps, uep_diag prefix
|
||||
survival (50 trials/setting), pass2_diag targeted sweep
|
||||
(t+1..t+8, 50 trials each)
|
||||
- Total matrix trials: 51,875 (+ diagnostics)
|
||||
- hot_chicago verification: BLOCKED — the old-VPS tunnel's SSH
|
||||
leg to 104.225.223.162 failed 4 times over ~1.5 h (banner-exchange
|
||||
timeout on the last attempt). Snapshot zips are staged on the
|
||||
old VPS (/tmp/lzply-*.zip) for a retry when the tunnel recovers.
|
||||
|
||||
## Rules of this branch
|
||||
|
||||
- Never touch `main` or the other coordinator's branches/checkouts.
|
||||
- No Reed-Solomon (the other job's territory).
|
||||
- No legacy support; the format may change freely.
|
||||
- Do not break the existing `-r` levels.
|
||||
- Honest negatives count: a family that loses on every axis is killed
|
||||
early and its numbers recorded.
|
||||
- After every push: zip snapshot to /root/git-backups/lzply/ on both
|
||||
servers (newest 7 kept); use /root/scripts/git-push-snapshot.sh
|
||||
when present, else temp-clone + zip + copy manually.
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
/* bch_wrap.c - BCH baseline codecs for the experiments harness.
|
||||
*
|
||||
* Two operating points of the same code, so the harness can show the
|
||||
* overhead/correction tradeoff honestly:
|
||||
*
|
||||
* bch-t<N> - exactly what lzply ships: bch_poly_for_data(blob, t)
|
||||
* picks the smallest parent covering the WHOLE blob, so a
|
||||
* 64 KiB blob is a single huge block (m=20, t=32 -> 80
|
||||
* parity bytes, 0.12% overhead, 32 correctable bits per
|
||||
* 64 KiB). Pass 2 (hash-gated candidates) is wired to
|
||||
* recover_verified, matching entry_decode().
|
||||
* bch1k-t<N> - same code, forced small blocks: pinned m=13 poly, so a
|
||||
* block holds 971 data bytes (t=32 -> 5.4% overhead).
|
||||
* This is the "what if we spent real redundancy" point.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "bch.h"
|
||||
#include "bch_polys.h"
|
||||
#include "sha256.h"
|
||||
|
||||
typedef struct {
|
||||
int t;
|
||||
const bch_poly_t *pinned; /* NULL = auto-pick (as-shipped) */
|
||||
} bch_priv_t;
|
||||
|
||||
static const bch_poly_t *poly_by_mt(int m, int t)
|
||||
{
|
||||
for (int i = 0; i < BCH_NPOLYS; i++)
|
||||
if (bch_polys[i].m == m && bch_polys[i].t == t)
|
||||
return &bch_polys[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static size_t bch_encode_fn(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
bch_priv_t *p = (bch_priv_t *)c->priv;
|
||||
const bch_poly_t *poly = p->pinned;
|
||||
if (!poly)
|
||||
poly = bch_poly_for_data(len, p->t);
|
||||
if (!poly)
|
||||
return 0;
|
||||
size_t slen = bch_encoded_len(len, poly);
|
||||
uint8_t *buf = (uint8_t *)malloc(slen ? slen : 1);
|
||||
if (!buf)
|
||||
return 0;
|
||||
if (bch_encode(data, len, poly, buf) != slen) {
|
||||
free(buf);
|
||||
return 0;
|
||||
}
|
||||
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static int bch_decode_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
bch_priv_t *p = (bch_priv_t *)c->priv;
|
||||
const bch_poly_t *poly = p->pinned;
|
||||
if (!poly)
|
||||
poly = bch_poly_for_data(orig_len, p->t);
|
||||
if (!poly)
|
||||
return -1;
|
||||
if (slen != bch_encoded_len(orig_len, poly))
|
||||
return -1;
|
||||
int corr = 0;
|
||||
int rc = bch_decode(stored, slen, orig_len, poly, out, &corr);
|
||||
if (corrected)
|
||||
*corrected = rc == 0 ? corr : -1;
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int bch_recover_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, const uint8_t want_sha[32],
|
||||
uint8_t *out)
|
||||
{
|
||||
bch_priv_t *p = (bch_priv_t *)c->priv;
|
||||
const bch_poly_t *poly = p->pinned;
|
||||
if (!poly)
|
||||
poly = bch_poly_for_data(orig_len, p->t);
|
||||
if (!poly)
|
||||
return -1;
|
||||
if (slen != bch_encoded_len(orig_len, poly))
|
||||
return -1;
|
||||
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * orig_len);
|
||||
if (!cands)
|
||||
return -1;
|
||||
int nc = bch_decode_candidates(stored, slen, orig_len, poly, cands,
|
||||
BCH_PASS2_MAX_CANDS);
|
||||
int found = -1;
|
||||
for (int i = 0; i < nc && found < 0; i++) {
|
||||
uint8_t h[32];
|
||||
lzply_sha256(cands + (size_t)i * orig_len, orig_len, h);
|
||||
if (memcmp(h, want_sha, 32) == 0)
|
||||
found = i;
|
||||
}
|
||||
if (found >= 0)
|
||||
memcpy(out, cands + (size_t)found * orig_len, orig_len);
|
||||
free(cands);
|
||||
return found >= 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
static void bch_destroy(ecc_codec_t *c)
|
||||
{
|
||||
free(c->priv);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
static ecc_codec_t *bch_new(int t, const bch_poly_t *pinned, const char *name)
|
||||
{
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
bch_priv_t *p = (bch_priv_t *)calloc(1, sizeof(*p));
|
||||
if (!c || !p) {
|
||||
free(c);
|
||||
free(p);
|
||||
return NULL;
|
||||
}
|
||||
p->t = t;
|
||||
p->pinned = pinned;
|
||||
c->name = name;
|
||||
c->desc = pinned ? "BCH, forced 1 KiB blocks" : "BCH as shipped in lzply";
|
||||
c->block_data = pinned ? bch_max_data(pinned) : 0;
|
||||
c->encode = bch_encode_fn;
|
||||
c->decode = bch_decode_fn;
|
||||
c->recover_verified = bch_recover_fn;
|
||||
c->destroy = bch_destroy;
|
||||
c->priv = p;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* As-shipped: auto-pick poly for the whole blob. */
|
||||
ecc_codec_t *bch_ship_new(int t)
|
||||
{
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name)
|
||||
return NULL;
|
||||
snprintf(name, 32, "bch-t%d", t);
|
||||
return bch_new(t, NULL, name);
|
||||
}
|
||||
|
||||
/* Forced small blocks: pinned m=13 poly (971 data bytes/block at any t). */
|
||||
ecc_codec_t *bch_1k_new(int t)
|
||||
{
|
||||
const bch_poly_t *poly = poly_by_mt(13, t);
|
||||
if (!poly)
|
||||
return NULL;
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name)
|
||||
return NULL;
|
||||
snprintf(name, 32, "bch1k-t%d", t);
|
||||
return bch_new(t, poly, name);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
/* bch_wrap.h - constructors for the BCH baseline codecs (bch_wrap.c). */
|
||||
#ifndef EXP_BCH_WRAP_H
|
||||
#define EXP_BCH_WRAP_H
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
ecc_codec_t *bch_ship_new(int t);
|
||||
ecc_codec_t *bch_1k_new(int t);
|
||||
|
||||
#endif /* EXP_BCH_WRAP_H */
|
||||
-338
@@ -1,338 +0,0 @@
|
||||
/* bench.c - corruption-matrix harness for the lzply ECC experiments.
|
||||
*
|
||||
* One invocation = one codec x one corruption setting x N trials.
|
||||
* Each trial: take a window of the corpus blob, encode it, corrupt the
|
||||
* stored bytes (random bit flips at a BER, or randomized byte bursts),
|
||||
* decode, and check exact recovery (memcmp + SHA-256). On decode
|
||||
* failure, the codec's recover_verified hook (if any) gets one shot
|
||||
* with the expected SHA -- that is how BCH pass 2 is credited.
|
||||
*
|
||||
* Usage:
|
||||
* bench --codec NAME --blob FILE [--size N] [--trials N] [--seed S]
|
||||
* (--ber X | --burst LEN,COUNT | --clean | --speed)
|
||||
* [--out results.csv]
|
||||
*
|
||||
* CSV (appended to --out, or stdout if omitted):
|
||||
* codec,corpus,blob_size,trials,mode,param,success,rescued,rate,
|
||||
* enc_MBps,dec_MBps,peak_rss_kb,overhead_pct
|
||||
*
|
||||
* Exit 0 on a completed run (even if recovery is 0 -- that is data),
|
||||
* 2 on usage/codec errors.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <inttypes.h>
|
||||
#include <time.h>
|
||||
#include <libgen.h>
|
||||
#include <sys/resource.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "sha256.h"
|
||||
|
||||
/* ---- codec factory (one constructor per family file) ---- */
|
||||
ecc_codec_t *bch_ship_new(int t);
|
||||
ecc_codec_t *bch_1k_new(int t);
|
||||
ecc_codec_t *interleave_new(int depth, int t);
|
||||
ecc_codec_t *ldpc_new(int rate_pct);
|
||||
|
||||
static ecc_codec_t *make_codec(const char *name)
|
||||
{
|
||||
int v;
|
||||
if (sscanf(name, "bch-t%d", &v) == 1)
|
||||
return bch_ship_new(v);
|
||||
if (sscanf(name, "bch1k-t%d", &v) == 1)
|
||||
return bch_1k_new(v);
|
||||
int d, t;
|
||||
if (sscanf(name, "intlv-d%d-bch1k-t%d", &d, &t) == 2)
|
||||
return interleave_new(d, t);
|
||||
if (sscanf(name, "ldpc-r%d", &v) == 1)
|
||||
return ldpc_new(v);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---- xorshift64* RNG ---- */
|
||||
static uint64_t rs = 0x12345678abcdefULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
static double now_s(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return ts.tv_sec + ts.tv_nsec * 1e-9;
|
||||
}
|
||||
|
||||
static uint8_t *read_file(const char *path, size_t *len_out)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f)
|
||||
return NULL;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n <= 0) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
uint8_t *buf = (uint8_t *)malloc((size_t)n);
|
||||
if (!buf) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
|
||||
free(buf);
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
fclose(f);
|
||||
*len_out = (size_t)n;
|
||||
return buf;
|
||||
}
|
||||
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr,
|
||||
"usage: bench --codec NAME --blob FILE [--size N] [--trials N]\n"
|
||||
" [--seed S] (--ber X | --burst LEN,COUNT | --clean | --speed)\n"
|
||||
" [--out results.csv]\n"
|
||||
" codecs: bch-t{2,4,8,16,32} bch1k-t{8,16,32}\n"
|
||||
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *codec_name = NULL, *blob_path = NULL, *out_path = NULL;
|
||||
size_t win_size = 65536;
|
||||
long trials = 200;
|
||||
uint64_t seed = 0x12345678abcdefULL;
|
||||
enum { M_BER, M_BURST, M_CLEAN, M_SPEED } mode = M_BER;
|
||||
double ber = 1e-3;
|
||||
long burst_len = 256, burst_count = 1;
|
||||
int nopass2 = 0;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--codec") && i + 1 < argc)
|
||||
codec_name = argv[++i];
|
||||
else if (!strcmp(argv[i], "--blob") && i + 1 < argc)
|
||||
blob_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--out") && i + 1 < argc)
|
||||
out_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--size") && i + 1 < argc)
|
||||
win_size = (size_t)strtoull(argv[++i], NULL, 0);
|
||||
else if (!strcmp(argv[i], "--trials") && i + 1 < argc)
|
||||
trials = strtol(argv[++i], NULL, 0);
|
||||
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
|
||||
seed = strtoull(argv[++i], NULL, 0);
|
||||
else if (!strcmp(argv[i], "--ber") && i + 1 < argc) {
|
||||
mode = M_BER;
|
||||
ber = strtod(argv[++i], NULL);
|
||||
} else if (!strcmp(argv[i], "--burst") && i + 1 < argc) {
|
||||
mode = M_BURST;
|
||||
char *a = argv[++i];
|
||||
burst_len = strtol(a, NULL, 0);
|
||||
char *comma = strchr(a, ',');
|
||||
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
|
||||
} else if (!strcmp(argv[i], "--nopass2")) {
|
||||
nopass2 = 1;
|
||||
} else if (!strcmp(argv[i], "--clean")) {
|
||||
mode = M_CLEAN;
|
||||
} else if (!strcmp(argv[i], "--speed")) {
|
||||
mode = M_SPEED;
|
||||
} else {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (!codec_name || !blob_path) {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
|
||||
size_t file_len = 0;
|
||||
uint8_t *file = read_file(blob_path, &file_len);
|
||||
if (!file || file_len <= win_size) {
|
||||
fprintf(stderr, "bench: cannot read blob %s (need > %zu bytes)\n",
|
||||
blob_path, win_size);
|
||||
return 2;
|
||||
}
|
||||
rs = seed ^ 0x9e3779b97f4a7c15ULL;
|
||||
|
||||
double t0 = now_s();
|
||||
ecc_codec_t *c = make_codec(codec_name);
|
||||
double init_s = now_s() - t0;
|
||||
if (!c) {
|
||||
fprintf(stderr, "bench: unknown codec %s\n", codec_name);
|
||||
return 2;
|
||||
}
|
||||
|
||||
const char *corpus = strrchr(blob_path, '/');
|
||||
corpus = corpus ? corpus + 1 : blob_path;
|
||||
|
||||
uint8_t *win = (uint8_t *)malloc(win_size);
|
||||
uint8_t *stored = NULL, *rx = NULL, *out = NULL;
|
||||
uint8_t want_sha[32];
|
||||
if (!win) return 2;
|
||||
out = (uint8_t *)malloc(win_size);
|
||||
if (!out) return 2;
|
||||
|
||||
long success = 0, rescued = 0;
|
||||
double enc_s = 0, dec_s = 0;
|
||||
double overhead = 0;
|
||||
int have_overhead = 0;
|
||||
|
||||
if (mode == M_SPEED) {
|
||||
/* encode/decode the whole file in windows, 5 passes */
|
||||
long passes = 5;
|
||||
size_t nw = file_len / win_size;
|
||||
double te0 = now_s();
|
||||
for (long p = 0; p < passes; p++)
|
||||
for (size_t w = 0; w < nw; w++) {
|
||||
free(stored);
|
||||
stored = NULL;
|
||||
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
|
||||
if (!sl) {
|
||||
fprintf(stderr, "bench: encode failed in speed mode\n");
|
||||
return 2;
|
||||
}
|
||||
if (!have_overhead) {
|
||||
overhead = c->overhead;
|
||||
have_overhead = 1;
|
||||
}
|
||||
}
|
||||
double te1 = now_s();
|
||||
double td0 = now_s();
|
||||
for (long p = 0; p < passes; p++)
|
||||
for (size_t w = 0; w < nw; w++) {
|
||||
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
|
||||
long corr = -1;
|
||||
if (c->decode(c, stored, sl, win_size, out, &corr) != 0 ||
|
||||
memcmp(out, file + w * win_size, win_size) != 0) {
|
||||
fprintf(stderr, "bench: speed-mode roundtrip FAILED\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
double td1 = now_s();
|
||||
double bytes = (double)passes * nw * win_size;
|
||||
double enc_mb = bytes / (te1 - te0) / 1e6;
|
||||
double dec_mb = bytes / (td1 - td0) / 1e6;
|
||||
struct rusage ru;
|
||||
getrusage(RUSAGE_SELF, &ru);
|
||||
fprintf(stderr,
|
||||
"SPEED %-28s corpus=%s win=%zu init=%.2fs enc=%.1f MB/s "
|
||||
"dec=%.1f MB/s rss=%ld KiB overhead=%.2f%%\n",
|
||||
codec_name, corpus, win_size, init_s, enc_mb, dec_mb,
|
||||
ru.ru_maxrss, overhead * 100.0);
|
||||
FILE *f = out_path ? fopen(out_path, "a") : stdout;
|
||||
if (f) {
|
||||
fprintf(f, "%s,%s,%zu,%ld,speed,init=%.2fs,0,0,1.000,"
|
||||
"%.2f,%.2f,%ld,%.4f\n",
|
||||
codec_name, corpus, win_size, passes, init_s, enc_mb,
|
||||
dec_mb, ru.ru_maxrss, overhead * 100.0);
|
||||
if (f != stdout)
|
||||
fclose(f);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* corruption trials */
|
||||
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
|
||||
rx = (uint8_t *)malloc(1 << 20); /* grown below if needed */
|
||||
for (long tr = 0; tr < trials; tr++) {
|
||||
size_t off = (size_t)(xr() % (file_len - win_size + 1));
|
||||
memcpy(win, file + off, win_size);
|
||||
lzply_sha256(win, win_size, want_sha);
|
||||
|
||||
double te0 = now_s();
|
||||
size_t slen = c->encode(c, win, win_size, &stored);
|
||||
double te1 = now_s();
|
||||
if (!slen) {
|
||||
fprintf(stderr, "bench: encode failed trial %ld\n", tr);
|
||||
return 2;
|
||||
}
|
||||
if (!have_overhead) {
|
||||
overhead = c->overhead;
|
||||
have_overhead = 1;
|
||||
}
|
||||
if (tr == 0) {
|
||||
free(rx);
|
||||
rx = (uint8_t *)malloc(slen);
|
||||
if (!rx)
|
||||
return 2;
|
||||
}
|
||||
memcpy(rx, stored, slen);
|
||||
|
||||
/* corrupt the stored bytes */
|
||||
if (mode == M_BER) {
|
||||
for (size_t i = 0; i < slen; i++) {
|
||||
uint8_t m = 0;
|
||||
for (int b = 0; b < 8; b++)
|
||||
if (xr() < ber_thr)
|
||||
m |= (uint8_t)(1u << b);
|
||||
rx[i] ^= m;
|
||||
}
|
||||
} else if (mode == M_BURST) {
|
||||
for (long b = 0; b < burst_count; b++) {
|
||||
if ((size_t)burst_len >= slen)
|
||||
continue;
|
||||
size_t start = (size_t)(xr() % (slen - (size_t)burst_len + 1));
|
||||
for (long k = 0; k < burst_len; k++)
|
||||
rx[start + k] = (uint8_t)(xr() & 0xff);
|
||||
}
|
||||
}
|
||||
|
||||
double td0 = now_s();
|
||||
long corr = -1;
|
||||
int rc = c->decode(c, rx, slen, win_size, out, &corr);
|
||||
int ok = (rc == 0 && memcmp(out, win, win_size) == 0);
|
||||
if (!ok && !nopass2 && c->recover_verified) {
|
||||
if (c->recover_verified(c, rx, slen, win_size, want_sha, out) == 0) {
|
||||
ok = 1;
|
||||
rescued++;
|
||||
}
|
||||
}
|
||||
double td1 = now_s();
|
||||
enc_s += te1 - te0;
|
||||
dec_s += td1 - td0;
|
||||
if (ok)
|
||||
success++;
|
||||
free(stored);
|
||||
stored = NULL;
|
||||
}
|
||||
|
||||
struct rusage ru;
|
||||
getrusage(RUSAGE_SELF, &ru);
|
||||
double rate = trials ? (double)success / (double)trials : 0;
|
||||
double enc_mb = enc_s > 0 ? (double)trials * win_size / enc_s / 1e6 : 0;
|
||||
double dec_mb = dec_s > 0 ? (double)trials * win_size / dec_s / 1e6 : 0;
|
||||
char param[64];
|
||||
if (mode == M_BER)
|
||||
snprintf(param, sizeof param, "ber=%g", ber);
|
||||
else if (mode == M_BURST)
|
||||
snprintf(param, sizeof param, "burst=%ldx%ld", burst_len, burst_count);
|
||||
else
|
||||
snprintf(param, sizeof param, "clean");
|
||||
const char *mname =
|
||||
mode == M_BER ? "ber" : mode == M_BURST ? "burst" : "clean";
|
||||
FILE *f = out_path ? fopen(out_path, "a") : stdout;
|
||||
if (f) {
|
||||
fprintf(f, "%s,%s,%zu,%ld,%s,%s,%ld,%ld,%.4f,%.2f,%.2f,%ld,%.4f\n",
|
||||
codec_name, corpus, win_size, trials, mname, param, success,
|
||||
rescued, rate, enc_mb, dec_mb, ru.ru_maxrss,
|
||||
overhead * 100.0);
|
||||
if (f != stdout)
|
||||
fclose(f);
|
||||
}
|
||||
fprintf(stderr, "%-28s %-12s %-14s %4ld trials rate=%.3f rescued=%ld "
|
||||
"enc=%.0fMB/s dec=%.0fMB/s ovh=%.2f%% rss=%ldKiB\n",
|
||||
codec_name, corpus, param, trials, rate, rescued, enc_mb, dec_mb,
|
||||
overhead * 100.0, ru.ru_maxrss);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/* ecc_iface.h - generic error-correction codec interface for the lzply
|
||||
* experiments harness (exp/). Every family under test implements this
|
||||
* interface so bench.c measures them all the same way: encode a blob,
|
||||
* corrupt the stored bytes, decode, and check exact recovery (SHA-256).
|
||||
*
|
||||
* A codec is a whole-blob transform: encode(data) -> stored bytes,
|
||||
* decode(stored) -> data or failure. Block structure inside is the
|
||||
* codec's business; the harness only sees blob in / blob out.
|
||||
*/
|
||||
#ifndef EXP_ECC_IFACE_H
|
||||
#define EXP_ECC_IFACE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct ecc_codec ecc_codec_t;
|
||||
struct ecc_codec {
|
||||
const char *name; /* short id, e.g. "bch-t32" (used in CSV output) */
|
||||
const char *desc; /* human-readable description */
|
||||
size_t block_data; /* nominal data bytes per code block (0 = whole blob) */
|
||||
/* encode data[0..len) -> malloc'd *out; return stored length, 0 on error.
|
||||
Sets c->overhead = stored/len - 1. */
|
||||
size_t (*encode)(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out);
|
||||
/* decode stored[0..slen) -> out[0..orig_len); 0 = exact recovery,
|
||||
-1 = failure. *corrected = bits/symbols corrected if known, else -1. */
|
||||
int (*decode)(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected);
|
||||
/* Optional second-chance recovery: given the expected SHA-256 of the
|
||||
original data, try harder (e.g. BCH pass-2 candidates) and use the
|
||||
first candidate that verifies. 0 = rescued, -1 = not. May be NULL. */
|
||||
int (*recover_verified)(ecc_codec_t *c, const uint8_t *stored,
|
||||
size_t slen, size_t orig_len,
|
||||
const uint8_t want_sha[32], uint8_t *out);
|
||||
double overhead; /* from the last encode() call */
|
||||
void (*destroy)(ecc_codec_t *c);
|
||||
void *priv;
|
||||
};
|
||||
|
||||
#endif /* EXP_ECC_IFACE_H */
|
||||
@@ -1,253 +0,0 @@
|
||||
/* interleave.c - byte interleaver over small-block BCH.
|
||||
*
|
||||
* The encoded stream (bch1k-t{T}: blocks of ~1 KiB data, t parity bits
|
||||
* each) is permuted before it hits the channel: the stream is cut into
|
||||
* groups of D consecutive blocks, each group written row-wise into a
|
||||
* D-row matrix (row j = block j) and read out column-wise. A burst of
|
||||
* L consecutive bytes in the channel then hits any one block at most
|
||||
* ceil(L/D) bytes -- about 4*L/D bit errors, since a randomized byte
|
||||
* flips ~4 bits -- instead of all L bytes landing in one block and
|
||||
* killing it outright. Zero extra parity: the interleaver is a pure
|
||||
* permutation, inverted on decode, so overhead is exactly the BCH
|
||||
* overhead and random-error performance is unchanged. The win is
|
||||
* purely burst tolerance, roughly a factor D in burst length.
|
||||
*
|
||||
* Groups are self-delimiting: block boundaries are recomputed from
|
||||
* orig_len, so the decoder knows every group's shape. The final group
|
||||
* may be short and the final block short; the column traversal simply
|
||||
* skips missing cells, which keeps the permutation exact with no
|
||||
* padding and no length change.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "bch.h"
|
||||
#include "bch_wrap.h"
|
||||
|
||||
typedef struct {
|
||||
ecc_codec_t *inner; /* bch1k-t{T} */
|
||||
int depth; /* blocks per interleave group */
|
||||
int t;
|
||||
} intlv_priv_t;
|
||||
|
||||
/* Permute the encoded stream (forward = interleave).
|
||||
* blocks[] holds the stored length of each block; nblocks total.
|
||||
* out must hold the same total length.
|
||||
*
|
||||
* Groups: blocks are cut into groups of `depth`, EXCEPT the final
|
||||
* partial group is merged into the previous one instead of standing
|
||||
* alone. A tiny tail group is the weak point: a burst landing in a
|
||||
* 4-block tail hits each of its blocks with L/4 bytes instead of
|
||||
* L/64, which is exactly why the first measurement showed 0.94
|
||||
* instead of 1.00 on 64-byte bursts (the 68-block blob ends in a
|
||||
* 4-block tail). Merging makes every group >= depth (the last may
|
||||
* exceed it); when nblocks <= depth there is a single group. */
|
||||
static void permute(const uint8_t *in, uint8_t *out, const size_t *blocks,
|
||||
size_t nblocks, int depth, int forward)
|
||||
{
|
||||
size_t *start = (size_t *)malloc((nblocks + 1) * sizeof(size_t));
|
||||
if (!start)
|
||||
return;
|
||||
start[0] = 0;
|
||||
for (size_t i = 0; i < nblocks; i++)
|
||||
start[i + 1] = start[i] + blocks[i];
|
||||
|
||||
/* group boundaries: groups of `depth`, last partial group merged
|
||||
into the previous one */
|
||||
size_t g0 = 0;
|
||||
while (g0 < nblocks) {
|
||||
size_t remain = nblocks - g0;
|
||||
size_t g = remain < (size_t)depth ? remain : (size_t)depth;
|
||||
/* If this would leave a short tail after this group, extend
|
||||
this group to absorb the tail. (Invariant: a short tail
|
||||
never survives an iteration, so no group is ever < depth
|
||||
except when the whole blob is.) */
|
||||
if (remain > (size_t)depth && remain - (size_t)depth < (size_t)depth)
|
||||
g = remain;
|
||||
size_t maxlen = 0;
|
||||
for (size_t j = 0; j < g; j++)
|
||||
if (blocks[g0 + j] > maxlen)
|
||||
maxlen = blocks[g0 + j];
|
||||
size_t goff = start[g0];
|
||||
size_t pos = 0;
|
||||
for (size_t c = 0; c < maxlen; c++) {
|
||||
for (size_t j = 0; j < g; j++) {
|
||||
if (c >= blocks[g0 + j])
|
||||
continue;
|
||||
size_t src = start[g0 + j] + c;
|
||||
size_t dst = goff + pos;
|
||||
if (forward)
|
||||
out[dst] = in[src];
|
||||
else
|
||||
out[src] = in[dst];
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
g0 += g;
|
||||
}
|
||||
free(start);
|
||||
}
|
||||
|
||||
static size_t intlv_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
uint8_t *enc = NULL;
|
||||
size_t slen = p->inner->encode(p->inner, data, len, &enc);
|
||||
if (!slen)
|
||||
return 0;
|
||||
/* block layout of the inner encoding */
|
||||
size_t bd = p->inner->block_data;
|
||||
size_t nblocks = (len + bd - 1) / bd;
|
||||
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
|
||||
if (!blocks) {
|
||||
free(enc);
|
||||
return 0;
|
||||
}
|
||||
/* stored length of block i: full blocks first, last may be short.
|
||||
The inner codec is bch_encode with a pinned poly, so stored
|
||||
length is a pure function of the block's data length. Recover
|
||||
it by splitting slen: all full blocks share one length. */
|
||||
size_t off = 0;
|
||||
for (size_t i = 0; i < nblocks; i++) {
|
||||
size_t dlen = len - i * bd < bd ? len - i * bd : bd;
|
||||
/* stored bytes for dlen data bytes under the pinned poly:
|
||||
ceil((8*dlen + r)/8); r = t*13 for m=13 */
|
||||
size_t r = (size_t)p->t * 13;
|
||||
blocks[i] = (8 * dlen + r + 7) / 8;
|
||||
off += blocks[i];
|
||||
}
|
||||
if (off != slen) { /* should not happen; bail out cleanly */
|
||||
free(blocks);
|
||||
free(enc);
|
||||
return 0;
|
||||
}
|
||||
uint8_t *buf = (uint8_t *)malloc(slen);
|
||||
if (!buf) {
|
||||
free(blocks);
|
||||
free(enc);
|
||||
return 0;
|
||||
}
|
||||
permute(enc, buf, blocks, nblocks, p->depth, 1);
|
||||
free(blocks);
|
||||
free(enc);
|
||||
c->overhead = p->inner->overhead;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static int intlv_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
size_t bd = p->inner->block_data;
|
||||
size_t nblocks = (orig_len + bd - 1) / bd;
|
||||
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
|
||||
if (!blocks)
|
||||
return -1;
|
||||
size_t off = 0;
|
||||
for (size_t i = 0; i < nblocks; i++) {
|
||||
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
|
||||
size_t r = (size_t)p->t * 13;
|
||||
blocks[i] = (8 * dlen + r + 7) / 8;
|
||||
off += blocks[i];
|
||||
}
|
||||
if (off != slen) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
uint8_t *deint = (uint8_t *)malloc(slen);
|
||||
if (!deint) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
permute(stored, deint, blocks, nblocks, p->depth, 0);
|
||||
free(blocks);
|
||||
int rc = p->inner->decode(p->inner, deint, slen, orig_len, out,
|
||||
corrected);
|
||||
free(deint);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int intlv_recover(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, const uint8_t want_sha[32],
|
||||
uint8_t *out)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
size_t bd = p->inner->block_data;
|
||||
size_t nblocks = (orig_len + bd - 1) / bd;
|
||||
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
|
||||
if (!blocks)
|
||||
return -1;
|
||||
size_t off = 0;
|
||||
for (size_t i = 0; i < nblocks; i++) {
|
||||
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
|
||||
size_t r = (size_t)p->t * 13;
|
||||
blocks[i] = (8 * dlen + r + 7) / 8;
|
||||
off += blocks[i];
|
||||
}
|
||||
if (off != slen) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
uint8_t *deint = (uint8_t *)malloc(slen);
|
||||
if (!deint) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
permute(stored, deint, blocks, nblocks, p->depth, 0);
|
||||
free(blocks);
|
||||
int rc = p->inner->recover_verified
|
||||
? p->inner->recover_verified(p->inner, deint, slen, orig_len,
|
||||
want_sha, out)
|
||||
: -1;
|
||||
free(deint);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void intlv_destroy(ecc_codec_t *c)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
if (p->inner)
|
||||
p->inner->destroy(p->inner);
|
||||
free(p);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *interleave_new(int depth, int t)
|
||||
{
|
||||
ecc_codec_t *inner = bch_1k_new(t);
|
||||
if (!inner)
|
||||
return NULL;
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
intlv_priv_t *p = (intlv_priv_t *)calloc(1, sizeof(*p));
|
||||
if (!c || !p) {
|
||||
free(c);
|
||||
free(p);
|
||||
inner->destroy(inner);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name) {
|
||||
free(c);
|
||||
free(p);
|
||||
inner->destroy(inner);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(name, 32, "intlv-d%d-bch1k-t%d", depth, t);
|
||||
p->inner = inner;
|
||||
p->depth = depth;
|
||||
p->t = t;
|
||||
c->name = name;
|
||||
c->desc = "byte interleaver over small-block BCH";
|
||||
c->block_data = inner->block_data;
|
||||
c->encode = intlv_encode;
|
||||
c->decode = intlv_decode;
|
||||
c->recover_verified = intlv_recover;
|
||||
c->destroy = intlv_destroy;
|
||||
c->priv = p;
|
||||
return c;
|
||||
}
|
||||
-565
@@ -1,565 +0,0 @@
|
||||
/* ldpc.c - regular LDPC codec for the experiments harness.
|
||||
*
|
||||
* Two operating points, both n=8192 bits, column weight 3:
|
||||
* ldpc-r90: m=768 checks, row weight 32, k=7424 bits (928 B),
|
||||
* rate 0.90625, overhead 10.34%.
|
||||
* ldpc-r95: m=384 checks, row weight 64, k=7808 bits (976 B),
|
||||
* rate 0.953125, overhead 4.92%.
|
||||
*
|
||||
* Construction: random regular parity-check matrix (configuration
|
||||
* model with 4-cycle rejection), fixed seed, so the code is identical
|
||||
* on every run and every server. Systematic encoding by Gauss-Jordan
|
||||
* reduction of H to [I | P] (one-time, at codec creation); decoding
|
||||
* is normalized min-sum belief propagation (factor 0.8), max 50
|
||||
* iterations, early stop when the syndrome is zero. Channel LLR uses
|
||||
* a fixed nominal crossover p0 = 1e-3 (the decoder does not know the
|
||||
* true BER; this is the honest setting for a storage channel).
|
||||
*
|
||||
* A blob is split into blocks of k data bytes; the last block is
|
||||
* zero-padded to k bytes (padding is discarded on decode). Stored
|
||||
* length per block is exactly n/8 = 1024 bytes.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
#define LDPC_N 8192
|
||||
#define LDPC_WC 3
|
||||
#define LDPC_MAX_ITER 50
|
||||
#define LDPC_MS_NORM 0.8f
|
||||
#define LDPC_P0 1e-3
|
||||
|
||||
typedef struct {
|
||||
int m; /* checks */
|
||||
int wr; /* row weight */
|
||||
int k; /* data bits */
|
||||
int kbytes; /* data bytes per block */
|
||||
int nedges;
|
||||
int *chk_var; /* m * wr: vars of each check */
|
||||
int *var_chk; /* n * wc: checks of each var */
|
||||
int *chk_edge; /* m * wr: edge id (var*wc+w) of each check entry */
|
||||
int *pivot_col; /* m: pivot column of each RREF row */
|
||||
uint64_t *enc_rows; /* m * kwords: RREF rows over data positions */
|
||||
int kwords;
|
||||
int *col_of_dp; /* k: column holding data position i */
|
||||
float *msg_vc; /* var->check, nedges */
|
||||
float *msg_cv; /* check->var, nedges */
|
||||
float *llr_ch; /* n */
|
||||
uint8_t *hard; /* n */
|
||||
} ldpc_t;
|
||||
|
||||
static void free_ldpc(ldpc_t *L)
|
||||
{
|
||||
if (!L)
|
||||
return;
|
||||
free(L->chk_var);
|
||||
free(L->var_chk);
|
||||
free(L->chk_edge);
|
||||
free(L->pivot_col);
|
||||
free(L->enc_rows);
|
||||
free(L->col_of_dp);
|
||||
free(L->msg_vc);
|
||||
free(L->msg_cv);
|
||||
free(L->llr_ch);
|
||||
free(L->hard);
|
||||
free(L);
|
||||
}
|
||||
|
||||
static uint64_t lrs = 0x243f6a8885a308d3ULL;
|
||||
static inline uint64_t lxr(void)
|
||||
{
|
||||
lrs ^= lrs << 13;
|
||||
lrs ^= lrs >> 7;
|
||||
lrs ^= lrs << 17;
|
||||
return lrs;
|
||||
}
|
||||
|
||||
/* ---- construction: progressive edge growth (PEG) ----
|
||||
* Edge by edge, each new edge of variable node v connects to the
|
||||
* check node farthest from v in the graph built so far (unreached
|
||||
* checks count as infinitely far), tie-broken by lowest check degree.
|
||||
* PEG never deadlocks (there is always a farthest check) and
|
||||
* maximizes girth by construction -- unlike greedy 4-cycle
|
||||
* rejection, which stalls in the endgame when the remaining stub
|
||||
* rows all close short cycles. Fallback: if every farthest check is
|
||||
* already full (cannot happen with balanced degrees, but be safe),
|
||||
* take the lowest-degree check overall. */
|
||||
static int build_H(ldpc_t *L, uint64_t seed)
|
||||
{
|
||||
int m = L->m, n = LDPC_N, wc = LDPC_WC, wr = L->wr;
|
||||
int *chk_deg = (int *)calloc((size_t)m, sizeof(int));
|
||||
int *var_deg = (int *)calloc((size_t)n, sizeof(int));
|
||||
int *dist = (int *)malloc((size_t)(n + m) * sizeof(int));
|
||||
int *queue = (int *)malloc((size_t)(n + m) * sizeof(int));
|
||||
if (!chk_deg || !var_deg || !dist || !queue) {
|
||||
free(chk_deg);
|
||||
free(var_deg);
|
||||
free(dist);
|
||||
free(queue);
|
||||
return -1;
|
||||
}
|
||||
lrs = seed;
|
||||
(void)lxr; /* seed only matters for tie-breaking below */
|
||||
for (int v = 0; v < n; v++) {
|
||||
for (int e = 0; e < wc; e++) {
|
||||
/* BFS from v over the graph built so far. Node ids:
|
||||
0..n-1 variables, n..n+m-1 checks. */
|
||||
for (int i = 0; i < n + m; i++)
|
||||
dist[i] = -1;
|
||||
int qh = 0, qt = 0;
|
||||
dist[v] = 0;
|
||||
queue[qt++] = v;
|
||||
int found_checks = 0;
|
||||
while (qh < qt && found_checks < m) {
|
||||
int u = queue[qh++];
|
||||
int d = dist[u];
|
||||
if (u < n) {
|
||||
for (int w = 0; w < var_deg[u]; w++) {
|
||||
int nid = n + L->var_chk[u * wc + w];
|
||||
if (dist[nid] < 0) {
|
||||
dist[nid] = d + 1;
|
||||
queue[qt++] = nid;
|
||||
found_checks++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int ch = u - n;
|
||||
for (int k = 0; k < chk_deg[ch]; k++) {
|
||||
int vv = L->chk_var[ch * wr + k];
|
||||
if (dist[vv] < 0) {
|
||||
dist[vv] = d + 1;
|
||||
queue[qt++] = vv;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* farthest distance among reached checks (-1 = unreached) */
|
||||
int bestd = -2, have_unreached = 0;
|
||||
for (int ch = 0; ch < m; ch++) {
|
||||
int d = dist[n + ch];
|
||||
if (d < 0) {
|
||||
have_unreached = 1;
|
||||
} else if (d > bestd) {
|
||||
bestd = d;
|
||||
}
|
||||
}
|
||||
int best = -1, bestdeg = wr + 1;
|
||||
for (int ch = 0; ch < m; ch++) {
|
||||
int d = dist[n + ch];
|
||||
int far = have_unreached ? (d < 0) : (d == bestd);
|
||||
if (!far)
|
||||
continue;
|
||||
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
|
||||
bestdeg = chk_deg[ch];
|
||||
best = ch;
|
||||
}
|
||||
}
|
||||
if (best < 0) {
|
||||
/* fallback: lowest-degree check anywhere */
|
||||
for (int ch = 0; ch < m; ch++)
|
||||
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
|
||||
bestdeg = chk_deg[ch];
|
||||
best = ch;
|
||||
}
|
||||
}
|
||||
if (best < 0) {
|
||||
free(chk_deg);
|
||||
free(var_deg);
|
||||
free(dist);
|
||||
free(queue);
|
||||
return -1;
|
||||
}
|
||||
L->var_chk[v * wc + var_deg[v]++] = best;
|
||||
L->chk_var[best * wr + chk_deg[best]++] = v;
|
||||
}
|
||||
}
|
||||
free(chk_deg);
|
||||
free(var_deg);
|
||||
free(dist);
|
||||
free(queue);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---- Gauss-Jordan: H -> RREF, record pivot columns + enc rows ---- */
|
||||
static int gauss_jordan(ldpc_t *L)
|
||||
{
|
||||
int m = L->m, n = LDPC_N;
|
||||
int words = (n + 63) / 64;
|
||||
uint64_t *H = (uint64_t *)calloc((size_t)m * words, sizeof(uint64_t));
|
||||
if (!H)
|
||||
return -1;
|
||||
for (int r = 0; r < m; r++)
|
||||
for (int k = 0; k < L->wr; k++) {
|
||||
int c = L->chk_var[r * L->wr + k];
|
||||
H[(size_t)r * words + c / 64] |= 1ULL << (c % 64);
|
||||
}
|
||||
int prow = 0;
|
||||
for (int col = 0; col < n && prow < m; col++) {
|
||||
int sel = -1;
|
||||
for (int r = prow; r < m; r++)
|
||||
if ((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL) {
|
||||
sel = r;
|
||||
break;
|
||||
}
|
||||
if (sel < 0)
|
||||
continue;
|
||||
if (sel != prow) {
|
||||
for (int w = 0; w < words; w++) {
|
||||
uint64_t t = H[(size_t)sel * words + w];
|
||||
H[(size_t)sel * words + w] = H[(size_t)prow * words + w];
|
||||
H[(size_t)prow * words + w] = t;
|
||||
}
|
||||
}
|
||||
for (int r = 0; r < m; r++) {
|
||||
if (r != prow &&
|
||||
((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL)) {
|
||||
for (int w = 0; w < words; w++)
|
||||
H[(size_t)r * words + w] ^=
|
||||
H[(size_t)prow * words + w];
|
||||
}
|
||||
}
|
||||
L->pivot_col[prow++] = col;
|
||||
}
|
||||
if (prow != m) {
|
||||
free(H);
|
||||
return -1; /* H not full rank */
|
||||
}
|
||||
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
|
||||
if (!is_pivot) {
|
||||
free(H);
|
||||
return -1;
|
||||
}
|
||||
for (int i = 0; i < m; i++)
|
||||
is_pivot[L->pivot_col[i]] = 1;
|
||||
L->col_of_dp = (int *)malloc((size_t)L->k * sizeof(int));
|
||||
if (!L->col_of_dp) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
int dp = 0;
|
||||
for (int c = 0; c < n; c++)
|
||||
if (!is_pivot[c])
|
||||
L->col_of_dp[dp++] = c;
|
||||
if (dp != L->k) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
L->kwords = (L->k + 63) / 64;
|
||||
L->enc_rows = (uint64_t *)calloc((size_t)m * L->kwords,
|
||||
sizeof(uint64_t));
|
||||
if (!L->enc_rows) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
int *data_pos = (int *)malloc((size_t)n * sizeof(int));
|
||||
if (!data_pos) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
dp = 0;
|
||||
for (int c = 0; c < n; c++)
|
||||
data_pos[c] = is_pivot[c] ? -1 : dp++;
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int c = 0; c < n; c++) {
|
||||
if (is_pivot[c])
|
||||
continue;
|
||||
if ((H[(size_t)i * words + c / 64] >> (c % 64)) & 1ULL) {
|
||||
int p = data_pos[c];
|
||||
L->enc_rows[(size_t)i * L->kwords + p / 64] |=
|
||||
1ULL << (p % 64);
|
||||
}
|
||||
}
|
||||
}
|
||||
free(data_pos);
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* bit helpers: MSB-first within each byte */
|
||||
static inline int get_bit(const uint8_t *buf, int i)
|
||||
{
|
||||
return (buf[i / 8] >> (7 - (i % 8))) & 1;
|
||||
}
|
||||
static inline void set_bit(uint8_t *buf, int i, int v)
|
||||
{
|
||||
if (v)
|
||||
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
|
||||
else
|
||||
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
|
||||
}
|
||||
|
||||
static size_t ldpc_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
ldpc_t *L = (ldpc_t *)c->priv;
|
||||
size_t nblocks = (len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
|
||||
size_t slen = nblocks * (LDPC_N / 8);
|
||||
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
|
||||
if (!buf)
|
||||
return 0;
|
||||
uint8_t *dbytes = (uint8_t *)calloc((size_t)L->kbytes, 1);
|
||||
uint64_t *dw = (uint64_t *)malloc((size_t)L->kwords * sizeof(uint64_t));
|
||||
if (!dbytes || !dw) {
|
||||
free(buf);
|
||||
free(dbytes);
|
||||
free(dw);
|
||||
return 0;
|
||||
}
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
size_t dlen = len - b * (size_t)L->kbytes < (size_t)L->kbytes
|
||||
? len - b * (size_t)L->kbytes
|
||||
: (size_t)L->kbytes;
|
||||
memset(dbytes, 0, (size_t)L->kbytes);
|
||||
memcpy(dbytes, data + b * (size_t)L->kbytes, dlen);
|
||||
/* data as words, bit i of the block -> word i/64, bit i%64 */
|
||||
memset(dw, 0, (size_t)L->kwords * sizeof(uint64_t));
|
||||
for (int i = 0; i < L->k; i++)
|
||||
if (get_bit(dbytes, i))
|
||||
dw[i / 64] |= 1ULL << (i % 64);
|
||||
uint8_t *cw = buf + b * (LDPC_N / 8);
|
||||
for (int i = 0; i < L->k; i++)
|
||||
set_bit(cw, L->col_of_dp[i], get_bit(dbytes, i));
|
||||
for (int i = 0; i < L->m; i++) {
|
||||
const uint64_t *row = L->enc_rows + (size_t)i * L->kwords;
|
||||
int acc = 0;
|
||||
for (int w = 0; w < L->kwords; w++)
|
||||
acc ^= __builtin_parityll(row[w] & dw[w]);
|
||||
set_bit(cw, L->pivot_col[i], acc);
|
||||
}
|
||||
}
|
||||
free(dbytes);
|
||||
free(dw);
|
||||
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static int ldpc_decode_block(ldpc_t *L, const uint8_t *cw_in,
|
||||
uint8_t *data_out, long *corrected_out)
|
||||
{
|
||||
int n = LDPC_N, m = L->m, wc = LDPC_WC, wr = L->wr;
|
||||
float L0 = (float)log((1.0 - LDPC_P0) / LDPC_P0);
|
||||
for (int i = 0; i < n; i++) {
|
||||
L->llr_ch[i] = get_bit(cw_in, i) ? -L0 : L0;
|
||||
for (int w = 0; w < wc; w++)
|
||||
L->msg_vc[i * wc + w] = L->llr_ch[i];
|
||||
}
|
||||
int converged = 0;
|
||||
for (int it = 0; it < LDPC_MAX_ITER && !converged; it++) {
|
||||
/* check update: two-minimum min-sum, via chk_edge ids */
|
||||
for (int j = 0; j < m; j++) {
|
||||
float min1 = 1e30f, min2 = 1e30f;
|
||||
int argmin1 = -1, sign = 1;
|
||||
for (int k = 0; k < wr; k++) {
|
||||
int e = L->chk_edge[j * wr + k];
|
||||
float x = L->msg_vc[e];
|
||||
float a = fabsf(x);
|
||||
if (a < min1) {
|
||||
min2 = min1;
|
||||
min1 = a;
|
||||
argmin1 = k;
|
||||
} else if (a < min2) {
|
||||
min2 = a;
|
||||
}
|
||||
if (x < 0)
|
||||
sign = -sign;
|
||||
}
|
||||
for (int k = 0; k < wr; k++) {
|
||||
int e = L->chk_edge[j * wr + k];
|
||||
float x = L->msg_vc[e];
|
||||
int s = sign;
|
||||
if (x < 0)
|
||||
s = -s;
|
||||
float mag = (k == argmin1 ? min2 : min1) * LDPC_MS_NORM;
|
||||
L->msg_cv[e] = s > 0 ? mag : -mag;
|
||||
}
|
||||
}
|
||||
/* hard decision + syndrome check */
|
||||
converged = 1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
float tot = L->llr_ch[i];
|
||||
for (int w = 0; w < wc; w++)
|
||||
tot += L->msg_cv[i * wc + w];
|
||||
L->hard[i] = tot < 0 ? 1 : 0;
|
||||
}
|
||||
for (int j = 0; j < m; j++) {
|
||||
int p = 0;
|
||||
for (int k = 0; k < wr; k++)
|
||||
p ^= L->hard[L->chk_var[j * wr + k]];
|
||||
if (p) {
|
||||
converged = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (converged)
|
||||
break;
|
||||
/* var->check messages for the next iteration */
|
||||
for (int i = 0; i < n; i++)
|
||||
for (int w = 0; w < wc; w++) {
|
||||
float tot = L->llr_ch[i];
|
||||
for (int w2 = 0; w2 < wc; w2++)
|
||||
if (w2 != w)
|
||||
tot += L->msg_cv[i * wc + w2];
|
||||
L->msg_vc[i * wc + w] = tot;
|
||||
}
|
||||
}
|
||||
if (!converged)
|
||||
return -1;
|
||||
long corr = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
if (L->hard[i] != get_bit(cw_in, i))
|
||||
corr++;
|
||||
if (corrected_out)
|
||||
*corrected_out = corr;
|
||||
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
|
||||
if (!is_pivot)
|
||||
return -1;
|
||||
for (int i = 0; i < m; i++)
|
||||
is_pivot[L->pivot_col[i]] = 1;
|
||||
int dp = 0;
|
||||
memset(data_out, 0, (size_t)L->kbytes);
|
||||
for (int col = 0; col < n; col++)
|
||||
if (!is_pivot[col])
|
||||
set_bit(data_out, dp++, L->hard[col]);
|
||||
free(is_pivot);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ldpc_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
ldpc_t *L = (ldpc_t *)c->priv;
|
||||
size_t nblocks = (orig_len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
|
||||
if (slen != nblocks * (LDPC_N / 8))
|
||||
return -1;
|
||||
long corr = 0;
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
uint8_t *db = (uint8_t *)malloc((size_t)L->kbytes);
|
||||
if (!db)
|
||||
return -1;
|
||||
long bc = 0;
|
||||
int rc = ldpc_decode_block(L, stored + b * (LDPC_N / 8), db, &bc);
|
||||
if (rc != 0) {
|
||||
free(db);
|
||||
if (corrected)
|
||||
*corrected = -1;
|
||||
return -1;
|
||||
}
|
||||
corr += bc;
|
||||
size_t dlen = orig_len - b * (size_t)L->kbytes < (size_t)L->kbytes
|
||||
? orig_len - b * (size_t)L->kbytes
|
||||
: (size_t)L->kbytes;
|
||||
memcpy(out + b * (size_t)L->kbytes, db, dlen);
|
||||
free(db);
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = corr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void ldpc_destroy(ecc_codec_t *c)
|
||||
{
|
||||
ldpc_t *L = (ldpc_t *)c->priv;
|
||||
free_ldpc(L);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *ldpc_new(int rate_pct)
|
||||
{
|
||||
int m, wr;
|
||||
const char *tag;
|
||||
if (rate_pct == 90) {
|
||||
m = 768;
|
||||
wr = 32;
|
||||
tag = "ldpc-r90";
|
||||
} else if (rate_pct == 95) {
|
||||
m = 384;
|
||||
wr = 64;
|
||||
tag = "ldpc-r95";
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
ldpc_t *L = (ldpc_t *)calloc(1, sizeof(*L));
|
||||
if (!L)
|
||||
return NULL;
|
||||
L->m = m;
|
||||
L->wr = wr;
|
||||
L->k = LDPC_N - m;
|
||||
L->kbytes = L->k / 8;
|
||||
L->nedges = LDPC_N * LDPC_WC;
|
||||
L->chk_var = (int *)malloc((size_t)m * wr * sizeof(int));
|
||||
L->var_chk = (int *)malloc((size_t)LDPC_N * LDPC_WC * sizeof(int));
|
||||
L->chk_edge = (int *)malloc((size_t)m * wr * sizeof(int));
|
||||
L->pivot_col = (int *)malloc((size_t)m * sizeof(int));
|
||||
L->msg_vc = (float *)malloc((size_t)L->nedges * sizeof(float));
|
||||
L->msg_cv = (float *)malloc((size_t)L->nedges * sizeof(float));
|
||||
L->llr_ch = (float *)malloc((size_t)LDPC_N * sizeof(float));
|
||||
L->hard = (uint8_t *)malloc((size_t)LDPC_N);
|
||||
if (!L->chk_var || !L->var_chk || !L->chk_edge || !L->pivot_col ||
|
||||
!L->msg_vc || !L->msg_cv || !L->llr_ch || !L->hard) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
int ok = -1;
|
||||
int attempt_used = -1;
|
||||
for (int attempt = 0; attempt < 10 && ok != 0; attempt++) {
|
||||
ok = build_H(L, 0x9e3779b97f4a7c15ULL +
|
||||
(uint64_t)attempt * 0x100000001b3ULL);
|
||||
attempt_used = attempt;
|
||||
}
|
||||
if (getenv("LDPC_DEBUG"))
|
||||
fprintf(stderr, "ldpc: build_H ok=%d attempts=%d\n", ok,
|
||||
attempt_used + 1);
|
||||
if (ok != 0) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
int gj = gauss_jordan(L);
|
||||
if (getenv("LDPC_DEBUG"))
|
||||
fprintf(stderr, "ldpc: gauss_jordan=%d\n", gj);
|
||||
if (gj != 0) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
/* edge ids for the decoder: chk_edge[j*wr+k] = var*wc+w */
|
||||
for (int j = 0; j < m; j++)
|
||||
for (int k = 0; k < wr; k++) {
|
||||
int v = L->chk_var[j * wr + k];
|
||||
int e = -1;
|
||||
for (int w = 0; w < LDPC_WC; w++)
|
||||
if (L->var_chk[v * LDPC_WC + w] == j)
|
||||
e = v * LDPC_WC + w;
|
||||
L->chk_edge[j * wr + k] = e;
|
||||
}
|
||||
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
if (!c) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(16);
|
||||
if (!name) {
|
||||
free_ldpc(L);
|
||||
free(c);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(name, 16, "%s", tag);
|
||||
c->name = name;
|
||||
c->desc = "regular LDPC, min-sum belief propagation";
|
||||
c->block_data = (size_t)L->kbytes;
|
||||
c->encode = ldpc_encode;
|
||||
c->decode = ldpc_decode;
|
||||
c->recover_verified = NULL;
|
||||
c->destroy = ldpc_destroy;
|
||||
c->priv = L;
|
||||
return c;
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/* ldpc_diag.c - diagnostic for the LDPC codec (NOT part of bench).
|
||||
* Encodes one fixed block, flips exactly k bits (k = 0..KMAX), decodes,
|
||||
* and reports the failure count per k. This separates "decoder bug"
|
||||
* (fails even at k=1..3) from "code weakness" (fails only near the
|
||||
* expected threshold). Usage: ldpc_diag <r90|r95> [kmax] [trials]
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "ecc_iface.h"
|
||||
|
||||
ecc_codec_t *ldpc_new(int rate_pct);
|
||||
|
||||
static uint64_t rs = 0xabcdef1234567ULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int rate = 90;
|
||||
int kmax = 24, trials = 100;
|
||||
if (argc > 1)
|
||||
rate = atoi(argv[1] + 1); /* "r90" -> 90 */
|
||||
if (argc > 2)
|
||||
kmax = atoi(argv[2]);
|
||||
if (argc > 3)
|
||||
trials = atoi(argv[3]);
|
||||
ecc_codec_t *c = ldpc_new(rate);
|
||||
if (!c) {
|
||||
fprintf(stderr, "ldpc_new failed\n");
|
||||
return 2;
|
||||
}
|
||||
size_t dlen = c->block_data;
|
||||
uint8_t *data = (uint8_t *)malloc(dlen);
|
||||
uint8_t *out = (uint8_t *)malloc(dlen);
|
||||
for (size_t i = 0; i < dlen; i++)
|
||||
data[i] = (uint8_t)(xr() & 0xff);
|
||||
uint8_t *stored = NULL;
|
||||
size_t slen = c->encode(c, data, dlen, &stored);
|
||||
if (!slen) {
|
||||
fprintf(stderr, "encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
printf("rate=%d block_data=%zu stored=%zu overhead=%.2f%%\n", rate,
|
||||
dlen, slen, c->overhead * 100.0);
|
||||
uint8_t *rx = (uint8_t *)malloc(slen);
|
||||
for (int k = 0; k <= kmax; k++) {
|
||||
int fails = 0;
|
||||
for (int t = 0; t < trials; t++) {
|
||||
memcpy(rx, stored, slen);
|
||||
/* flip k distinct random bits */
|
||||
for (int f = 0; f < k; f++) {
|
||||
size_t p = (size_t)(xr() % (slen * 8));
|
||||
rx[p / 8] ^= (uint8_t)(1u << (7 - (p % 8)));
|
||||
}
|
||||
long corr = -1;
|
||||
int rc = c->decode(c, rx, slen, dlen, out, &corr);
|
||||
if (rc != 0 || memcmp(out, data, dlen) != 0)
|
||||
fails++;
|
||||
}
|
||||
printf("k=%2d fails=%d/%d\n", k, fails, trials);
|
||||
fflush(stdout);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/bin/bash
|
||||
# mkcorpora.sh - build the experiment corpora in exp/corpora/.
|
||||
# text.raw / text.lz : English-ish text (docs + sources)
|
||||
# bin.raw / bin.lz : ELF binaries
|
||||
# rand.raw / rand.lz : seeded pseudo-random bytes (incompressible)
|
||||
# lz files are lzip -9 of the raw files: that is what lzply actually
|
||||
# protects (the compressed blob), plus the raw files for stored entries.
|
||||
set -e
|
||||
cd "$(dirname "$0")/corpora"
|
||||
# text: repo docs/sources + system docs
|
||||
{ find /opt/lzply-exp-ecc -name "*.md" -o -name "*.c" -o -name "*.h" | sort | xargs cat
|
||||
find /usr/share/doc -type f -size -200k 2>/dev/null | head -200 | sort | xargs cat 2>/dev/null
|
||||
find /usr/include -name "*.h" 2>/dev/null | head -300 | sort | xargs cat 2>/dev/null
|
||||
} > text.raw
|
||||
head -c 4194304 text.raw > text4m.raw && mv text4m.raw text.raw
|
||||
# binaries: ELF files from /bin and /usr/bin
|
||||
{ for f in /bin/* /usr/bin/*; do
|
||||
[ -f "$f" ] && head -c1 "$f" | grep -q . && file "$f" 2>/dev/null | grep -q ELF && cat "$f"
|
||||
done
|
||||
} > bin.raw 2>/dev/null
|
||||
head -c 4194304 bin.raw > bin4m.raw && mv bin4m.raw bin.raw
|
||||
# random: seeded python (reproducible on both servers)
|
||||
python3 -c "import random; random.seed(1234); open(\"rand.raw\",\"wb\").write(bytes(random.getrandbits(8) for _ in range(4194304)))"
|
||||
for f in text bin rand; do
|
||||
lzip -9 -f -c "$f.raw" > "$f.lz" 2>/dev/null || lzip -9 -c "$f.raw" > "$f.lz"
|
||||
done
|
||||
ls -la
|
||||
@@ -1,89 +0,0 @@
|
||||
/* pass2_diag.c - targeted test of BCH pass-2 (hash-gated candidates).
|
||||
* Encodes one bch1k block, flips exactly k bits (k around t), and
|
||||
* reports: pass-1 success, and pass-2 rescue (candidate verifies
|
||||
* against the SHA-256 of the original). This separates "pass 2 is
|
||||
* weak" from "the harness wiring is broken".
|
||||
* Usage: pass2_diag <t> [kmax] [trials]
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "bch.h"
|
||||
#include "bch_polys.h"
|
||||
#include "sha256.h"
|
||||
|
||||
static uint64_t rs = 0xabcdef1234567ULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
static const bch_poly_t *poly_by_mt(int m, int t)
|
||||
{
|
||||
for (int i = 0; i < BCH_NPOLYS; i++)
|
||||
if (bch_polys[i].m == m && bch_polys[i].t == t)
|
||||
return &bch_polys[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int t = argc > 1 ? atoi(argv[1]) : 16;
|
||||
int kmax = argc > 2 ? atoi(argv[2]) : t + 8;
|
||||
int trials = argc > 3 ? atoi(argv[3]) : 50;
|
||||
const bch_poly_t *p = poly_by_mt(13, t);
|
||||
if (!p) {
|
||||
fprintf(stderr, "no poly m=13 t=%d\n", t);
|
||||
return 2;
|
||||
}
|
||||
size_t dlen = bch_max_data(p);
|
||||
size_t slen = bch_block_stored_len(dlen, p);
|
||||
uint8_t *data = (uint8_t *)malloc(dlen);
|
||||
uint8_t *stored = (uint8_t *)malloc(slen);
|
||||
uint8_t *rx = (uint8_t *)malloc(slen);
|
||||
uint8_t *out = (uint8_t *)malloc(dlen);
|
||||
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * dlen);
|
||||
for (size_t i = 0; i < dlen; i++)
|
||||
data[i] = (uint8_t)(xr() & 0xff);
|
||||
if (bch_encode_block(data, dlen, p, stored) != 0) {
|
||||
fprintf(stderr, "encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
uint8_t want[32];
|
||||
lzply_sha256(data, dlen, want);
|
||||
printf("t=%d block_data=%zu stored=%zu\n", t, dlen, slen);
|
||||
for (int k = t - 2; k <= kmax; k++) {
|
||||
int p1 = 0, rescued = 0;
|
||||
for (int tr = 0; tr < trials; tr++) {
|
||||
memcpy(rx, stored, slen);
|
||||
for (int f = 0; f < k; f++) {
|
||||
size_t pos = (size_t)(xr() % (slen * 8));
|
||||
rx[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
|
||||
}
|
||||
int corr = -1;
|
||||
if (bch_decode_block(rx, slen, dlen, p, out, &corr) == 0 &&
|
||||
memcmp(out, data, dlen) == 0) {
|
||||
p1++;
|
||||
continue;
|
||||
}
|
||||
int nc = bch_decode_block_candidates(rx, slen, dlen, p, cands,
|
||||
BCH_PASS2_MAX_CANDS);
|
||||
for (int i = 0; i < nc; i++) {
|
||||
uint8_t h[32];
|
||||
lzply_sha256(cands + (size_t)i * dlen, dlen, h);
|
||||
if (memcmp(h, want, 32) == 0) {
|
||||
rescued++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
printf("k=%2d pass1=%d/%d rescued=%d/%d\n", k, p1, trials, rescued,
|
||||
trials);
|
||||
fflush(stdout);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#!/bin/bash
|
||||
# run_matrix.sh - full corruption matrix for a list of codecs.
|
||||
# Usage: run_matrix.sh <corpus> <blobsize> <trials> <outfile> <codec...>
|
||||
# Each codec x setting is its own bench invocation; xargs -P spreads
|
||||
# them over all cores. Pass 2 is OFF for the matrix (too slow at scale);
|
||||
# rescue rates are measured separately by run_pass2.sh.
|
||||
set -u
|
||||
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
{
|
||||
for CODEC in "$@"; do
|
||||
for BER in 1e-5 1e-4 1e-3 3e-3 1e-2; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --nopass2 --out $OUT"
|
||||
done
|
||||
for B in "16,1" "64,1" "256,1" "1024,1" "64,4"; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --nopass2 --out $OUT"
|
||||
done
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --clean --out $OUT"
|
||||
done
|
||||
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/matrix.log'
|
||||
echo "matrix done: $OUT"
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/bash
|
||||
# run_pass2.sh - BCH pass-2 rescue rates, small trial count (pass 2 is
|
||||
# slow; 25 trials per setting is enough to see rescues).
|
||||
# Usage: run_pass2.sh <corpus> <blobsize> <trials> <outfile> <codec...>
|
||||
set -u
|
||||
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
{
|
||||
for CODEC in "$@"; do
|
||||
for BER in 1e-4 1e-3 3e-3; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --out $OUT"
|
||||
done
|
||||
for B in "64,1" "256,1"; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --out $OUT"
|
||||
done
|
||||
done
|
||||
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/pass2.log'
|
||||
echo "pass2 done: $OUT"
|
||||
+19
-1
@@ -5,7 +5,7 @@ CC = gcc
|
||||
CFLAGS = -O3 -Wall -Wextra -march=native
|
||||
LDLIBS = -llz -lm
|
||||
|
||||
TOOLS = rans_tool dict bchcheck
|
||||
TOOLS = rans_tool lzrans bwt ppm dict bchcheck
|
||||
all: $(TOOLS)
|
||||
|
||||
rans.o: rans.c rans.h
|
||||
@@ -14,6 +14,24 @@ rans.o: rans.c rans.h
|
||||
rans_tool: rans_tool.o rans.o
|
||||
$(CC) $(CFLAGS) -o $@ rans_tool.o rans.o
|
||||
|
||||
lzrans.o: lzrans.c rans.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzrans.c
|
||||
|
||||
lzrans: lzrans.o rans.o
|
||||
$(CC) $(CFLAGS) -o $@ lzrans.o rans.o
|
||||
|
||||
bwt.o: bwt.c rans.h
|
||||
$(CC) $(CFLAGS) -c -o $@ bwt.c
|
||||
|
||||
bwt: bwt.o rans.o
|
||||
$(CC) $(CFLAGS) -o $@ bwt.o rans.o
|
||||
|
||||
ppm.o: ppm.c
|
||||
$(CC) $(CFLAGS) -c -o $@ ppm.c
|
||||
|
||||
ppm: ppm.o
|
||||
$(CC) $(CFLAGS) -o $@ ppm.o $(LDLIBS)
|
||||
|
||||
dict.o: dict.c
|
||||
$(CC) $(CFLAGS) -c -o $@ dict.c
|
||||
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
# lzply compression experiments (branch experiments/comp)
|
||||
|
||||
> Integrated onto current main (`experiments/integration`, LZPL v5):
|
||||
> the winners here are the dictionary transform (code-only) and the
|
||||
> rANS core as infrastructure. lzrans, BWT, and PPM were measured,
|
||||
> rejected, and their code was NOT carried over — see
|
||||
> `docs/INTEGRATION.md`.
|
||||
|
||||
Prototypes for open-ended compression research. Each tool is standalone:
|
||||
`tool c|o in out`, `tool d in out`. Shared rANS core in rans.[ch].
|
||||
`bench.py <name> <enc> <dec> [corpora...]` times (best of 3), sizes,
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
/* bwt.c - BWT + MTF + run-length tokens + rANS prototype.
|
||||
* Classic bzip2-style pipeline, written from scratch: suffix array by
|
||||
* doubling with counting sort, Burrows-Wheeler transform, move-to-front,
|
||||
* runs of >=4 identical MTF values tokenised as (value, 256, k),
|
||||
* rANS over a 257-symbol alphabet.
|
||||
* Usage: bwt c in out | bwt d in out
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "rans.h"
|
||||
|
||||
#define NSYM 257
|
||||
#define RUN_SYM 256
|
||||
|
||||
static uint8_t *slurp(const char *path, size_t *n) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) { perror(path); exit(2); }
|
||||
fseek(f, 0, SEEK_END);
|
||||
long sz = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
uint8_t *b = malloc(sz ? (size_t)sz : 1);
|
||||
if (!b) exit(2);
|
||||
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
|
||||
fclose(f);
|
||||
*n = (size_t)sz;
|
||||
return b;
|
||||
}
|
||||
|
||||
static void spit(const char *path, const uint8_t *b, size_t n) {
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f) { perror(path); exit(2); }
|
||||
if (n && fwrite(b, 1, n, f) != n) exit(2);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void put32(uint8_t *p, uint32_t v) {
|
||||
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8);
|
||||
p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
|
||||
}
|
||||
static uint32_t get32(const uint8_t *p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
/* Counting-sort SA by key array key[SA[i]] (keys in [0, kmax]).
|
||||
* sa2 is scratch. */
|
||||
static void csort(int32_t *sa, int32_t *sa2, const int32_t *key, size_t n,
|
||||
int32_t kmax, int32_t *cnt) {
|
||||
memset(cnt, 0, (size_t)(kmax + 1) * sizeof *cnt);
|
||||
for (size_t i = 0; i < n; i++) cnt[key[sa[i]]]++;
|
||||
int32_t sum = 0;
|
||||
for (int32_t k = 0; k <= kmax; k++) {
|
||||
int32_t c = cnt[k];
|
||||
cnt[k] = sum;
|
||||
sum += c;
|
||||
}
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
int32_t s = sa[i];
|
||||
sa2[cnt[key[s]]++] = s;
|
||||
}
|
||||
memcpy(sa, sa2, n * sizeof *sa);
|
||||
}
|
||||
|
||||
/* Suffix array of the CYCLIC rotations, by doubling with wraparound
|
||||
* rank lookups: rotation i is compared via data[i+k mod n], so the
|
||||
* order is rotation order (what BWT needs), not linear-suffix order.
|
||||
* A linear sort puts "a" before "a bandana", but cyclically
|
||||
* "a bandanabanan" < "abanana bandan"; a sentinel does not fix this
|
||||
* either ("a$" < "a bandana$" truncates the comparison). Periodic
|
||||
* rotations stay tied, which is harmless: identical rotations have
|
||||
* identical BWT chars. */
|
||||
static int32_t *build_sa(const uint8_t *d, size_t n) {
|
||||
int32_t *sa = malloc(n * sizeof *sa);
|
||||
int32_t *sa2 = malloc(n * sizeof *sa2);
|
||||
int32_t *rank = malloc(n * sizeof *rank);
|
||||
int32_t *tmp = malloc(n * sizeof *tmp);
|
||||
int32_t *key = malloc(n * sizeof *key);
|
||||
int32_t *cnt = malloc((n + 258) * sizeof *cnt);
|
||||
if (!sa || !sa2 || !rank || !tmp || !key || !cnt) exit(2);
|
||||
int32_t maxrank = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
sa[i] = (int32_t)i;
|
||||
rank[i] = d[i];
|
||||
if (d[i] > maxrank) maxrank = d[i];
|
||||
}
|
||||
for (size_t k = 1; k < n; k *= 2) {
|
||||
/* sort by second key rank[(i+k) % n], then first key rank[i];
|
||||
* (i+k) % n without division: i+k < 2n always (k < n). */
|
||||
for (size_t i = 0; i + k < n; i++) key[i] = rank[i + k] + 1;
|
||||
for (size_t i = n - k; i < n; i++) key[i] = rank[i + k - n] + 1;
|
||||
csort(sa, sa2, key, n, maxrank + 1, cnt);
|
||||
for (size_t i = 0; i < n; i++) key[i] = rank[i] + 1;
|
||||
csort(sa, sa2, key, n, maxrank + 1, cnt);
|
||||
tmp[sa[0]] = 0;
|
||||
int32_t r = 0;
|
||||
for (size_t i = 1; i < n; i++) {
|
||||
int32_t x = sa[i - 1], y = sa[i];
|
||||
size_t x2 = (size_t)x + k; if (x2 >= n) x2 -= n;
|
||||
size_t y2 = (size_t)y + k; if (y2 >= n) y2 -= n;
|
||||
if (rank[x] != rank[y] || rank[x2] != rank[y2]) r++;
|
||||
tmp[y] = r;
|
||||
}
|
||||
memcpy(rank, tmp, n * sizeof *rank);
|
||||
maxrank = r;
|
||||
if (maxrank == (int32_t)n - 1) break;
|
||||
}
|
||||
free(sa2); free(rank); free(tmp); free(key); free(cnt);
|
||||
return sa;
|
||||
}
|
||||
|
||||
static int encode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
uint32_t primary = 0;
|
||||
uint8_t *bwt = malloc(n ? n : 1);
|
||||
if (!bwt) return 2;
|
||||
if (n > 0) {
|
||||
int32_t *sa = build_sa(in, n);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
size_t sv = (size_t)sa[i];
|
||||
if (sv == 0) primary = (uint32_t)i;
|
||||
bwt[i] = in[(sv + n - 1) % n];
|
||||
}
|
||||
free(sa);
|
||||
}
|
||||
/* MTF */
|
||||
uint8_t *mtf = malloc(n ? n : 1);
|
||||
uint8_t lst[256];
|
||||
for (int i = 0; i < 256; i++) lst[i] = (uint8_t)i;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
uint8_t c = bwt[i];
|
||||
int pos = 0;
|
||||
while (lst[pos] != c) pos++;
|
||||
mtf[i] = (uint8_t)pos;
|
||||
memmove(lst + 1, lst, (size_t)pos);
|
||||
lst[0] = c;
|
||||
}
|
||||
free(bwt);
|
||||
/* run tokenisation into 257-symbol stream */
|
||||
uint16_t *tok = malloc((2 * n + 2) * sizeof *tok);
|
||||
if (!tok) return 2;
|
||||
size_t nt = 0, i = 0;
|
||||
while (i < n) {
|
||||
size_t j = i + 1;
|
||||
while (j < n && mtf[j] == mtf[i]) j++;
|
||||
size_t run = j - i;
|
||||
if (run < 4) {
|
||||
for (size_t k = 0; k < run; k++) tok[nt++] = mtf[i];
|
||||
} else {
|
||||
tok[nt++] = mtf[i];
|
||||
size_t rem = run - 1;
|
||||
while (rem > 0) {
|
||||
size_t chunk = rem > 255 ? 255 : rem;
|
||||
tok[nt++] = RUN_SYM;
|
||||
tok[nt++] = (uint16_t)chunk;
|
||||
rem -= chunk;
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
free(mtf);
|
||||
uint16_t freq[NSYM];
|
||||
rans_freq_n(tok, nt, NSYM, freq);
|
||||
uint8_t *stream = malloc(2 * nt + 64);
|
||||
if (!stream) return 2;
|
||||
size_t slen = rans_encode_raw_n(tok, nt, freq, NSYM, stream);
|
||||
size_t hdr = 4 + 4 + 4 + 4 + NSYM * 2;
|
||||
uint8_t *out = malloc(hdr + slen);
|
||||
if (!out) return 2;
|
||||
uint8_t *p = out;
|
||||
memcpy(p, "BWTX", 4); p += 4;
|
||||
put32(p, (uint32_t)n); p += 4;
|
||||
put32(p, primary); p += 4;
|
||||
put32(p, (uint32_t)nt); p += 4;
|
||||
for (int s = 0; s < NSYM; s++) {
|
||||
p[0] = (uint8_t)freq[s]; p[1] = (uint8_t)(freq[s] >> 8); p += 2;
|
||||
}
|
||||
memcpy(p, stream, slen); p += slen;
|
||||
spit(outpath, out, (size_t)(p - out));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int decode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
size_t hdr = 4 + 4 + 4 + 4 + NSYM * 2;
|
||||
if (n < hdr || memcmp(in, "BWTX", 4) != 0) {
|
||||
fprintf(stderr, "bwt: bad magic/header\n");
|
||||
return 3;
|
||||
}
|
||||
const uint8_t *p = in + 4;
|
||||
uint32_t orig = get32(p); p += 4;
|
||||
uint32_t primary = get32(p); p += 4;
|
||||
uint32_t nt = get32(p); p += 4;
|
||||
uint16_t freq[NSYM];
|
||||
for (int s = 0; s < NSYM; s++) {
|
||||
freq[s] = (uint16_t)(p[0] | (p[1] << 8)); p += 2;
|
||||
}
|
||||
uint16_t *tok = malloc((nt ? nt : 1) * sizeof *tok);
|
||||
if (!tok) return 2;
|
||||
if (rans_decode_raw_n(p, n - hdr, freq, NSYM, tok, nt) != 0) {
|
||||
fprintf(stderr, "bwt: token stream corrupt\n");
|
||||
return 3;
|
||||
}
|
||||
/* expand runs to MTF values */
|
||||
uint8_t *mtf = malloc(orig ? orig : 1);
|
||||
if (!mtf) return 2;
|
||||
size_t m = 0;
|
||||
uint8_t last = 0;
|
||||
for (uint32_t i = 0; i < nt; i++) {
|
||||
uint16_t s = tok[i];
|
||||
if (s == RUN_SYM) {
|
||||
if (i + 1 >= nt) { fprintf(stderr, "bwt: truncated run\n"); return 3; }
|
||||
uint16_t k = tok[++i];
|
||||
if (m + k > orig) { fprintf(stderr, "bwt: run overrun\n"); return 3; }
|
||||
memset(mtf + m, last, k);
|
||||
m += k;
|
||||
} else {
|
||||
if (m >= orig) { fprintf(stderr, "bwt: mtf overrun\n"); return 3; }
|
||||
last = (uint8_t)s;
|
||||
mtf[m++] = last;
|
||||
}
|
||||
}
|
||||
if (m != orig) { fprintf(stderr, "bwt: short mtf %zu != %u\n", m, orig); return 3; }
|
||||
free(tok);
|
||||
/* inverse MTF */
|
||||
uint8_t *bwt = malloc(orig ? orig : 1);
|
||||
uint8_t lst[256];
|
||||
for (int i = 0; i < 256; i++) lst[i] = (uint8_t)i;
|
||||
for (size_t k = 0; k < orig; k++) {
|
||||
uint8_t c = lst[mtf[k]];
|
||||
bwt[k] = c;
|
||||
memmove(lst + 1, lst, mtf[k]);
|
||||
lst[0] = c;
|
||||
}
|
||||
free(mtf);
|
||||
/* inverse BWT via LF-mapping */
|
||||
uint8_t *out = malloc(orig ? orig : 1);
|
||||
if (!out) return 2;
|
||||
if (orig > 0) {
|
||||
int32_t cnt[256] = {0};
|
||||
for (size_t k = 0; k < orig; k++) cnt[bwt[k]]++;
|
||||
int32_t C[256];
|
||||
int32_t sum = 0;
|
||||
for (int c = 0; c < 256; c++) { C[c] = sum; sum += cnt[c]; }
|
||||
int32_t *lf = malloc(orig * sizeof *lf);
|
||||
if (!lf) return 2;
|
||||
int32_t occ[256] = {0};
|
||||
for (size_t k = 0; k < orig; k++) {
|
||||
uint8_t c = bwt[k];
|
||||
lf[k] = C[c] + occ[c]++;
|
||||
}
|
||||
size_t idx = primary;
|
||||
for (size_t k = orig; k-- > 0;) {
|
||||
out[k] = bwt[idx];
|
||||
idx = (size_t)lf[idx];
|
||||
}
|
||||
free(lf);
|
||||
}
|
||||
spit(outpath, out, orig);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
|
||||
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
|
||||
: decode(argv[2], argv[3]);
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
/* lzrans.c - LZ77 + rANS prototype for the lzply compression research.
|
||||
* Hash-chain match finder (1 MiB window), lazy matching (`c`) or
|
||||
* optimal parsing (`o`, DP over match costs; per candidate only its
|
||||
* full length is considered), deflate-style length codes (29) and
|
||||
* log2 distance codes (21, dist up to 2^20). Three streams: litlen
|
||||
* (286 symbols: 0-255 literal, 256-284 length code, 285 end), dist
|
||||
* (21 symbols), extra bits (raw LSB-first). Each token stream is
|
||||
* rANS-coded with its own transmitted freq table.
|
||||
* Usage: lzrans c|o in out | lzrans d in out
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "rans.h"
|
||||
|
||||
#define WINDOW (1u << 20)
|
||||
#define MAX_MATCH 258
|
||||
#define MIN_MATCH 3
|
||||
#define HASH_BITS 16
|
||||
#define HASH_SIZE (1u << HASH_BITS)
|
||||
#define LITLEN_END 285
|
||||
|
||||
static const int len_base[29] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,
|
||||
43,51,59,67,83,99,115,131,163,195,227,258};
|
||||
static const int len_extra[29] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,
|
||||
4,4,4,4,5,5,5,5,0};
|
||||
|
||||
static int len_code_of(int len) {
|
||||
int c = 0;
|
||||
while (c < 28 && len >= len_base[c + 1]) c++;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* dist 1..2^20 -> code 0..19, extra bits = code, base = 1<<code */
|
||||
static int dist_code_of(uint32_t d) { return 31 - __builtin_clz(d); }
|
||||
|
||||
static uint8_t *slurp(const char *path, size_t *n) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) { perror(path); exit(2); }
|
||||
fseek(f, 0, SEEK_END);
|
||||
long sz = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
uint8_t *b = malloc(sz ? (size_t)sz : 1);
|
||||
if (!b) exit(2);
|
||||
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
|
||||
fclose(f);
|
||||
*n = (size_t)sz;
|
||||
return b;
|
||||
}
|
||||
|
||||
static void spit(const char *path, const uint8_t *b, size_t n) {
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f) { perror(path); exit(2); }
|
||||
if (n && fwrite(b, 1, n, f) != n) exit(2);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void put32(uint8_t *p, uint32_t v) {
|
||||
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8);
|
||||
p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
|
||||
}
|
||||
static uint32_t get32(const uint8_t *p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
/* ---- bit writer (LSB-first) ---- */
|
||||
typedef struct { uint8_t *buf; size_t len, cap; uint32_t acc; int nbits; } bitw_t;
|
||||
static void bitw_put(bitw_t *w, uint32_t v, int n) {
|
||||
w->acc |= v << w->nbits;
|
||||
w->nbits += n;
|
||||
while (w->nbits >= 8) {
|
||||
if (w->len == w->cap) {
|
||||
w->cap = w->cap ? w->cap * 2 : 4096;
|
||||
w->buf = realloc(w->buf, w->cap);
|
||||
if (!w->buf) exit(2);
|
||||
}
|
||||
w->buf[w->len++] = (uint8_t)(w->acc & 0xff);
|
||||
w->acc >>= 8;
|
||||
w->nbits -= 8;
|
||||
}
|
||||
}
|
||||
static void bitw_flush(bitw_t *w) {
|
||||
if (w->nbits) {
|
||||
if (w->len == w->cap) {
|
||||
w->cap = w->cap ? w->cap * 2 : 4096;
|
||||
w->buf = realloc(w->buf, w->cap);
|
||||
if (!w->buf) exit(2);
|
||||
}
|
||||
w->buf[w->len++] = (uint8_t)(w->acc & 0xff);
|
||||
w->acc = 0; w->nbits = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- bit reader (LSB-first) ---- */
|
||||
typedef struct { const uint8_t *buf; size_t len, pos; uint32_t acc; int nbits; } bitr_t;
|
||||
static uint32_t bitr_get(bitr_t *r, int n) {
|
||||
while (r->nbits < n) {
|
||||
uint32_t b = r->pos < r->len ? r->buf[r->pos++] : 0;
|
||||
r->acc |= b << r->nbits;
|
||||
r->nbits += 8;
|
||||
}
|
||||
uint32_t v = n == 32 ? r->acc : (r->acc & ((n == 0) ? 0u : ((1u << n) - 1)));
|
||||
r->acc >>= n;
|
||||
r->nbits -= n;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* ---- match finder ---- */
|
||||
typedef struct {
|
||||
const uint8_t *data;
|
||||
size_t n;
|
||||
int32_t head[HASH_SIZE];
|
||||
int32_t *prev;
|
||||
} mf_t;
|
||||
|
||||
static uint32_t hash4(const uint8_t *p) {
|
||||
uint32_t v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
return (v * 2654435761u) >> (32 - HASH_BITS);
|
||||
}
|
||||
|
||||
static void mf_insert(mf_t *m, size_t pos) {
|
||||
if (pos + 4 > m->n) return;
|
||||
uint32_t h = hash4(m->data + pos);
|
||||
m->prev[pos] = m->head[h];
|
||||
m->head[h] = (int32_t)pos;
|
||||
}
|
||||
|
||||
/* Longest match at pos (limit capped by caller). Returns 0 if < 3. */
|
||||
static int mf_find(mf_t *m, size_t pos, int limit, int max_chain,
|
||||
int *dist_out) {
|
||||
if (pos + 4 > m->n) return 0;
|
||||
uint32_t h = hash4(m->data + pos);
|
||||
int32_t cand = m->head[h];
|
||||
int best = 2, bestd = 0, chain = 0;
|
||||
while (cand >= 0 && chain++ < max_chain) {
|
||||
size_t c = (size_t)cand;
|
||||
size_t d = pos - c;
|
||||
if (d > WINDOW) break;
|
||||
if (best >= 3) {
|
||||
/* quick reject: byte at best must match */
|
||||
if (c + (size_t)best >= m->n ||
|
||||
m->data[c + best] != m->data[pos + best]) {
|
||||
cand = m->prev[cand];
|
||||
continue;
|
||||
}
|
||||
}
|
||||
int l = 0;
|
||||
while (l < limit && pos + (size_t)l < m->n &&
|
||||
m->data[c + l] == m->data[pos + l]) l++;
|
||||
if (l > best) {
|
||||
best = l; bestd = (int)d;
|
||||
if (best >= limit) break;
|
||||
}
|
||||
cand = m->prev[cand];
|
||||
}
|
||||
*dist_out = bestd;
|
||||
return best >= MIN_MATCH ? best : 0;
|
||||
}
|
||||
|
||||
/* ---- token streams ---- */
|
||||
typedef struct {
|
||||
uint16_t *litlen; size_t nlit, clit;
|
||||
uint16_t *dist; size_t ndist, cdist;
|
||||
bitw_t bits;
|
||||
} toks_t;
|
||||
|
||||
static void toks_init(toks_t *t, size_t n) {
|
||||
t->clit = n + 2; t->litlen = malloc(t->clit * 2);
|
||||
t->cdist = n / 3 + 2; t->dist = malloc(t->cdist * 2);
|
||||
t->nlit = t->ndist = 0;
|
||||
memset(&t->bits, 0, sizeof t->bits);
|
||||
if (!t->litlen || !t->dist) exit(2);
|
||||
}
|
||||
static void toks_lit(toks_t *t, uint8_t b) { t->litlen[t->nlit++] = b; }
|
||||
static void toks_match(toks_t *t, int len, int dist) {
|
||||
int lc = len_code_of(len);
|
||||
t->litlen[t->nlit++] = (uint16_t)(256 + lc);
|
||||
int dc = dist_code_of((uint32_t)dist);
|
||||
t->dist[t->ndist++] = (uint16_t)dc;
|
||||
bitw_put(&t->bits, (uint32_t)(len - len_base[lc]), len_extra[lc]);
|
||||
bitw_put(&t->bits, (uint32_t)(dist - (1 << dc)), dc);
|
||||
}
|
||||
|
||||
/* ---- lazy parse ---- */
|
||||
static void parse_lazy(mf_t *m, toks_t *t) {
|
||||
size_t n = m->n, pos = 0;
|
||||
while (pos < n) {
|
||||
if (n - pos < MIN_MATCH) { toks_lit(t, m->data[pos++]); continue; }
|
||||
int d1 = 0;
|
||||
int l1 = mf_find(m, pos, (int)(n - pos < MAX_MATCH ? n - pos : MAX_MATCH),
|
||||
128, &d1);
|
||||
if (l1 >= MIN_MATCH) {
|
||||
mf_insert(m, pos);
|
||||
int l2 = 0, d2 = 0;
|
||||
if (n - (pos + 1) >= MIN_MATCH)
|
||||
l2 = mf_find(m, pos + 1,
|
||||
(int)(n - pos - 1 < MAX_MATCH ? n - pos - 1 : MAX_MATCH),
|
||||
128, &d2);
|
||||
if (l2 > l1) { toks_lit(t, m->data[pos]); pos++; continue; }
|
||||
toks_match(t, l1, d1);
|
||||
for (int k = 1; k < l1; k++) mf_insert(m, pos + (size_t)k);
|
||||
pos += (size_t)l1;
|
||||
} else {
|
||||
toks_lit(t, m->data[pos]);
|
||||
mf_insert(m, pos);
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- optimal parse (DP; per candidate only its full length) ---- */
|
||||
static void parse_opt(mf_t *m, toks_t *t) {
|
||||
size_t n = m->n;
|
||||
double *cost = malloc((n + 1) * sizeof *cost);
|
||||
int32_t *ch_len = malloc((n + 1) * sizeof *ch_len);
|
||||
int32_t *ch_dist = malloc((n + 1) * sizeof *ch_dist);
|
||||
if (!cost || !ch_len || !ch_dist) exit(2);
|
||||
for (size_t i = 0; i <= n; i++) { cost[i] = 1e100; ch_len[i] = 0; ch_dist[i] = 0; }
|
||||
cost[0] = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (cost[i] < 1e99 && n - i >= MIN_MATCH) {
|
||||
/* literal */
|
||||
if (cost[i] + 9.0 < cost[i + 1]) {
|
||||
cost[i + 1] = cost[i] + 9.0; ch_len[i + 1] = 0;
|
||||
}
|
||||
/* matches: walk the chain, full length per candidate */
|
||||
if (i + 4 <= n) {
|
||||
uint32_t h = hash4(m->data + i);
|
||||
int32_t cand = m->head[h];
|
||||
int chain = 0, best = 2;
|
||||
int limit = (int)(n - i < MAX_MATCH ? n - i : MAX_MATCH);
|
||||
while (cand >= 0 && chain++ < 32) {
|
||||
size_t c = (size_t)cand;
|
||||
size_t d = i - c;
|
||||
if (d > WINDOW) break;
|
||||
if (best >= 3 && (c + (size_t)best >= n ||
|
||||
m->data[c + best] != m->data[i + best])) {
|
||||
cand = m->prev[cand];
|
||||
continue;
|
||||
}
|
||||
int l = 0;
|
||||
while (l < limit && m->data[c + l] == m->data[i + l]) l++;
|
||||
if (l >= MIN_MATCH && l > 2) {
|
||||
int lc = len_code_of(l);
|
||||
int dc = dist_code_of((uint32_t)d);
|
||||
double mc = cost[i] + 8.0 + len_extra[lc] + 5.0 + dc;
|
||||
if (mc < cost[i + (size_t)l]) {
|
||||
cost[i + (size_t)l] = mc;
|
||||
ch_len[i + (size_t)l] = l;
|
||||
ch_dist[i + (size_t)l] = (int32_t)d;
|
||||
}
|
||||
if (l > best) best = l;
|
||||
}
|
||||
cand = m->prev[cand];
|
||||
}
|
||||
}
|
||||
}
|
||||
mf_insert(m, i);
|
||||
}
|
||||
/* reconstruct backwards, then reverse */
|
||||
size_t pos = n, nt = 0;
|
||||
uint16_t *rl = malloc((n + 1) * 2);
|
||||
int32_t *rd = malloc((n + 1) * 4);
|
||||
int32_t *rlen = malloc((n + 1) * 4);
|
||||
if (!rl || !rd || !rlen) exit(2);
|
||||
while (pos > 0) {
|
||||
int32_t l = ch_len[pos];
|
||||
if (l == 0) { rl[nt] = m->data[pos - 1]; rlen[nt] = 0; rd[nt] = 0; nt++; pos--; }
|
||||
else { rl[nt] = 0; rlen[nt] = l; rd[nt] = ch_dist[pos]; nt++; pos -= (size_t)l; }
|
||||
}
|
||||
for (size_t k = nt; k-- > 0;) {
|
||||
if (rlen[k] == 0) toks_lit(t, (uint8_t)rl[k]);
|
||||
else toks_match(t, rlen[k], rd[k]);
|
||||
}
|
||||
free(cost); free(ch_len); free(ch_dist); free(rl); free(rd); free(rlen);
|
||||
}
|
||||
|
||||
static int encode(const char *inpath, const char *outpath, int optimal) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
mf_t m;
|
||||
m.data = in; m.n = n;
|
||||
memset(m.head, 0xff, sizeof m.head);
|
||||
m.prev = malloc((n ? n : 1) * sizeof *m.prev);
|
||||
if (!m.prev) return 2;
|
||||
toks_t t;
|
||||
toks_init(&t, n);
|
||||
if (optimal) parse_opt(&m, &t);
|
||||
else parse_lazy(&m, &t);
|
||||
t.litlen[t.nlit++] = LITLEN_END;
|
||||
bitw_flush(&t.bits);
|
||||
|
||||
uint16_t freq_ll[286], freq_d[21];
|
||||
rans_freq_n(t.litlen, t.nlit, 286, freq_ll);
|
||||
rans_freq_n(t.dist, t.ndist, 21, freq_d);
|
||||
uint8_t *s_ll = malloc(2 * t.nlit + 64);
|
||||
uint8_t *s_d = malloc(2 * t.ndist + 64);
|
||||
if (!s_ll || !s_d) return 2;
|
||||
size_t sll_len = rans_encode_raw_n(t.litlen, t.nlit, freq_ll, 286, s_ll);
|
||||
size_t sd_len = rans_encode_raw_n(t.dist, t.ndist, freq_d, 21, s_d);
|
||||
|
||||
size_t hdr = 4 + 4 + 1 + 20 + 286 * 2 + 21 * 2;
|
||||
size_t total = hdr + sll_len + sd_len + t.bits.len;
|
||||
uint8_t *out = malloc(total ? total : 1);
|
||||
if (!out) return 2;
|
||||
uint8_t *p = out;
|
||||
memcpy(p, "LZRA", 4); p += 4;
|
||||
put32(p, (uint32_t)n); p += 4;
|
||||
*p++ = optimal ? 1 : 0;
|
||||
put32(p, (uint32_t)t.nlit); p += 4;
|
||||
put32(p, (uint32_t)t.ndist); p += 4;
|
||||
put32(p, (uint32_t)t.bits.len); p += 4;
|
||||
put32(p, (uint32_t)sll_len); p += 4;
|
||||
put32(p, (uint32_t)sd_len); p += 4;
|
||||
for (int s = 0; s < 286; s++) { p[0] = (uint8_t)freq_ll[s]; p[1] = (uint8_t)(freq_ll[s] >> 8); p += 2; }
|
||||
for (int s = 0; s < 21; s++) { p[0] = (uint8_t)freq_d[s]; p[1] = (uint8_t)(freq_d[s] >> 8); p += 2; }
|
||||
memcpy(p, s_ll, sll_len); p += sll_len;
|
||||
memcpy(p, s_d, sd_len); p += sd_len;
|
||||
memcpy(p, t.bits.buf, t.bits.len); p += t.bits.len;
|
||||
spit(outpath, out, (size_t)(p - out));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int decode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
size_t hdr = 4 + 4 + 1 + 20 + 286 * 2 + 21 * 2;
|
||||
if (n < hdr || memcmp(in, "LZRA", 4) != 0) {
|
||||
fprintf(stderr, "lzrans: bad magic/header\n");
|
||||
return 3;
|
||||
}
|
||||
const uint8_t *p = in + 4;
|
||||
uint32_t orig = get32(p); p += 4;
|
||||
p++; /* mode */
|
||||
uint32_t nlit = get32(p); p += 4;
|
||||
uint32_t ndist = get32(p); p += 4;
|
||||
uint32_t ebits = get32(p); p += 4;
|
||||
uint32_t sll_len = get32(p); p += 4;
|
||||
uint32_t sd_len = get32(p); p += 4;
|
||||
uint16_t freq_ll[286], freq_d[21];
|
||||
for (int s = 0; s < 286; s++) { freq_ll[s] = (uint16_t)(p[0] | (p[1] << 8)); p += 2; }
|
||||
for (int s = 0; s < 21; s++) { freq_d[s] = (uint16_t)(p[0] | (p[1] << 8)); p += 2; }
|
||||
if ((size_t)(p - in) + sll_len + sd_len + ebits != n) {
|
||||
fprintf(stderr, "lzrans: truncated file\n");
|
||||
return 3;
|
||||
}
|
||||
uint16_t *litlen = malloc((nlit ? nlit : 1) * 2);
|
||||
uint16_t *dist = malloc((ndist ? ndist : 1) * 2);
|
||||
if (!litlen || !dist) return 2;
|
||||
if (rans_decode_raw_n(p, sll_len, freq_ll, 286, litlen, nlit) != 0) {
|
||||
fprintf(stderr, "lzrans: litlen stream corrupt\n");
|
||||
return 3;
|
||||
}
|
||||
p += sll_len;
|
||||
if (rans_decode_raw_n(p, sd_len, freq_d, 21, dist, ndist) != 0) {
|
||||
fprintf(stderr, "lzrans: dist stream corrupt\n");
|
||||
return 3;
|
||||
}
|
||||
p += sd_len;
|
||||
uint8_t *out = malloc(orig ? orig : 1);
|
||||
if (!out) return 2;
|
||||
bitr_t br = { p, ebits, 0, 0, 0 };
|
||||
size_t opos = 0, di = 0;
|
||||
for (uint32_t i = 0; i < nlit; i++) {
|
||||
uint16_t s = litlen[i];
|
||||
if (s < 256) {
|
||||
if (opos >= orig) { fprintf(stderr, "lzrans: overrun\n"); return 3; }
|
||||
out[opos++] = (uint8_t)s;
|
||||
} else if (s == LITLEN_END) {
|
||||
break;
|
||||
} else {
|
||||
int lc = s - 256;
|
||||
if (lc < 0 || lc > 28 || di >= ndist) {
|
||||
fprintf(stderr, "lzrans: bad token\n");
|
||||
return 3;
|
||||
}
|
||||
int len = len_base[lc] + (int)bitr_get(&br, len_extra[lc]);
|
||||
int dc = dist[di++];
|
||||
if (dc < 0 || dc > 20) { fprintf(stderr, "lzrans: bad dist\n"); return 3; }
|
||||
int d = (1 << dc) + (int)bitr_get(&br, dc);
|
||||
if ((size_t)d > opos || opos + (size_t)len > orig) {
|
||||
fprintf(stderr, "lzrans: bad match\n");
|
||||
return 3;
|
||||
}
|
||||
for (int k = 0; k < len; k++) {
|
||||
out[opos] = out[opos - (size_t)d];
|
||||
opos++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (opos != orig) {
|
||||
fprintf(stderr, "lzrans: short output %zu != %u\n", opos, orig);
|
||||
return 3;
|
||||
}
|
||||
spit(outpath, out, opos);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 4) {
|
||||
fprintf(stderr, "usage: %s c|o|d in out\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
if (argv[1][0] == 'c') return encode(argv[2], argv[3], 0);
|
||||
if (argv[1][0] == 'o') return encode(argv[2], argv[3], 1);
|
||||
if (argv[1][0] == 'd') return decode(argv[2], argv[3]);
|
||||
fprintf(stderr, "usage: %s c|o|d in out\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
/* ppm.c - order-2 PPM + arithmetic coding prototype (context mixing).
|
||||
* Three context levels (order-2, order-1, order-0) with escape to the
|
||||
* next level; escape mass = number of distinct symbols seen in the
|
||||
* context. Order -1 is uniform over 256 symbols. The coder is the
|
||||
* classic Witten-Neal-Cleary 32-bit arithmetic coder (E1/E2/E3).
|
||||
* Counts are updated in ALL levels after every symbol, on both sides.
|
||||
* Usage: ppm c in out | ppm d in out
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define ESC 256
|
||||
#define NSYM 257
|
||||
|
||||
static uint8_t *slurp(const char *path, size_t *n) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) { perror(path); exit(2); }
|
||||
fseek(f, 0, SEEK_END);
|
||||
long sz = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
uint8_t *b = malloc(sz ? (size_t)sz : 1);
|
||||
if (!b) exit(2);
|
||||
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
|
||||
fclose(f);
|
||||
*n = (size_t)sz;
|
||||
return b;
|
||||
}
|
||||
|
||||
static void spit(const char *path, const uint8_t *b, size_t n) {
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f) { perror(path); exit(2); }
|
||||
if (n && fwrite(b, 1, n, f) != n) exit(2);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
/* ---- bit writer (MSB-first) ---- */
|
||||
typedef struct {
|
||||
uint8_t *buf; size_t len, cap;
|
||||
uint32_t acc; int nbits;
|
||||
} bitw_t;
|
||||
|
||||
static void bitw_put(bitw_t *w, int bit) {
|
||||
w->acc = (w->acc << 1) | (uint32_t)bit;
|
||||
if (++w->nbits == 8) {
|
||||
if (w->len == w->cap) {
|
||||
w->cap = w->cap ? w->cap * 2 : 65536;
|
||||
w->buf = realloc(w->buf, w->cap);
|
||||
if (!w->buf) exit(2);
|
||||
}
|
||||
w->buf[w->len++] = (uint8_t)w->acc;
|
||||
w->acc = 0; w->nbits = 0;
|
||||
}
|
||||
}
|
||||
static void bitw_flush(bitw_t *w) {
|
||||
if (w->nbits) {
|
||||
w->acc <<= (8 - w->nbits);
|
||||
if (w->len == w->cap) {
|
||||
w->cap = w->cap ? w->cap * 2 : 65536;
|
||||
w->buf = realloc(w->buf, w->cap);
|
||||
if (!w->buf) exit(2);
|
||||
}
|
||||
w->buf[w->len++] = (uint8_t)w->acc;
|
||||
w->acc = 0; w->nbits = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- bit reader (MSB-first, 0 past EOF) ---- */
|
||||
typedef struct {
|
||||
const uint8_t *buf; size_t len, pos;
|
||||
uint32_t acc; int nbits;
|
||||
} bitr_t;
|
||||
|
||||
static int bitr_get(bitr_t *r) {
|
||||
if (r->nbits == 0) {
|
||||
uint8_t b = r->pos < r->len ? r->buf[r->pos++] : 0;
|
||||
r->acc = b; r->nbits = 8;
|
||||
}
|
||||
int bit = (int)((r->acc >> 7) & 1);
|
||||
r->acc <<= 1; r->nbits--;
|
||||
return bit;
|
||||
}
|
||||
|
||||
/* ---- arithmetic coder ---- */
|
||||
typedef struct {
|
||||
uint32_t low, high;
|
||||
int follow;
|
||||
bitw_t *w;
|
||||
} enc_t;
|
||||
|
||||
static void enc_bit(enc_t *e, int bit) {
|
||||
bitw_put(e->w, bit);
|
||||
while (e->follow > 0) { bitw_put(e->w, !bit); e->follow--; }
|
||||
}
|
||||
|
||||
static void enc_symbol(enc_t *e, uint32_t cum_lo, uint32_t cum_hi, uint32_t total) {
|
||||
uint64_t range = (uint64_t)(e->high - e->low) + 1;
|
||||
e->high = e->low + (uint32_t)(range * cum_hi / total) - 1;
|
||||
e->low = e->low + (uint32_t)(range * cum_lo / total);
|
||||
for (;;) {
|
||||
if (e->high < 0x80000000u) {
|
||||
enc_bit(e, 0);
|
||||
} else if (e->low >= 0x80000000u) {
|
||||
enc_bit(e, 1);
|
||||
e->low -= 0x80000000u; e->high -= 0x80000000u;
|
||||
} else if (e->low >= 0x40000000u && e->high < 0xC0000000u) {
|
||||
e->follow++;
|
||||
e->low -= 0x40000000u; e->high -= 0x40000000u;
|
||||
} else break;
|
||||
e->low <<= 1; e->high = (e->high << 1) | 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void enc_flush(enc_t *e) {
|
||||
e->follow++;
|
||||
if (e->low < 0x40000000u) enc_bit(e, 0);
|
||||
else enc_bit(e, 1);
|
||||
bitw_flush(e->w);
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
uint32_t low, high, value;
|
||||
bitr_t *r;
|
||||
} dec_t;
|
||||
|
||||
static void dec_init(dec_t *d, bitr_t *r) {
|
||||
d->low = 0; d->high = 0xFFFFFFFFu; d->value = 0; d->r = r;
|
||||
for (int i = 0; i < 32; i++) d->value = (d->value << 1) | (uint32_t)bitr_get(r);
|
||||
}
|
||||
|
||||
static uint32_t dec_cum(dec_t *d, uint32_t total) {
|
||||
uint64_t range = (uint64_t)(d->high - d->low) + 1;
|
||||
return (uint32_t)(((uint64_t)(d->value - d->low + 1) * total - 1) / range);
|
||||
}
|
||||
|
||||
static void dec_update(dec_t *d, uint32_t cum_lo, uint32_t cum_hi, uint32_t total) {
|
||||
uint64_t range = (uint64_t)(d->high - d->low) + 1;
|
||||
d->high = d->low + (uint32_t)(range * cum_hi / total) - 1;
|
||||
d->low = d->low + (uint32_t)(range * cum_lo / total);
|
||||
for (;;) {
|
||||
if (d->high < 0x80000000u) {
|
||||
/* no shift */
|
||||
} else if (d->low >= 0x80000000u) {
|
||||
d->value -= 0x80000000u; d->low -= 0x80000000u; d->high -= 0x80000000u;
|
||||
} else if (d->low >= 0x40000000u && d->high < 0xC0000000u) {
|
||||
d->value -= 0x40000000u; d->low -= 0x40000000u; d->high -= 0x40000000u;
|
||||
} else break;
|
||||
d->low <<= 1; d->high = (d->high << 1) | 1;
|
||||
d->value = (d->value << 1) | (uint32_t)bitr_get(d->r);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- PPM model ----
|
||||
* cnt0[256], cnt1[256][256], cnt2[65536][256] (uint32), totals and
|
||||
* distinct-symbol counts per context. ~64 MB for cnt2. */
|
||||
static uint32_t *cnt2; /* [65536][256] */
|
||||
static uint32_t cnt1[256][256];
|
||||
static uint32_t cnt0[256];
|
||||
static uint32_t tot2[65536];
|
||||
static uint32_t tot1[256];
|
||||
static uint32_t tot0;
|
||||
static uint32_t dist2[65536];
|
||||
static uint32_t dist1[256];
|
||||
static uint32_t dist0;
|
||||
|
||||
static void model_reset(void) {
|
||||
memset(cnt1, 0, sizeof cnt1);
|
||||
memset(cnt0, 0, sizeof cnt0);
|
||||
memset(tot2, 0, sizeof tot2);
|
||||
memset(tot1, 0, sizeof tot1);
|
||||
memset(dist2, 0, sizeof dist2);
|
||||
memset(dist1, 0, sizeof dist1);
|
||||
tot0 = 0; dist0 = 0;
|
||||
if (cnt2) memset(cnt2, 0, (size_t)65536 * 256 * sizeof *cnt2);
|
||||
}
|
||||
|
||||
static void model_update(int b, int p2, int p1) {
|
||||
uint32_t c2 = (uint32_t)((p2 << 8) | p1);
|
||||
uint32_t *row2 = cnt2 + (size_t)c2 * 256;
|
||||
if (row2[b] == 0) dist2[c2]++;
|
||||
row2[b]++;
|
||||
tot2[c2]++;
|
||||
if (cnt1[p1][b] == 0) dist1[p1]++;
|
||||
cnt1[p1][b]++;
|
||||
tot1[p1]++;
|
||||
if (cnt0[b] == 0) dist0++;
|
||||
cnt0[b]++;
|
||||
tot0++;
|
||||
}
|
||||
|
||||
/* Cumulative interval of symbol s (0..255) or ESC in a level.
|
||||
* cnt: per-symbol counts; dist: escape mass; tot: symbol total.
|
||||
* total = tot + dist. Returns 0 if the symbol has freq 0. */
|
||||
static int level_interval(const uint32_t *cnt, uint32_t dist, uint32_t tot,
|
||||
int s, uint32_t *lo, uint32_t *hi, uint32_t *total) {
|
||||
*total = tot + dist;
|
||||
uint32_t acc = 0;
|
||||
if (s == ESC) {
|
||||
for (int i = 0; i < 256; i++) acc += cnt[i];
|
||||
*lo = acc; *hi = acc + dist;
|
||||
return dist > 0;
|
||||
}
|
||||
for (int i = 0; i < s; i++) acc += cnt[i];
|
||||
*lo = acc; *hi = acc + cnt[s];
|
||||
return cnt[s] > 0;
|
||||
}
|
||||
|
||||
/* Find the symbol for a cum value in a level; fills lo/hi/total. */
|
||||
static int level_lookup(const uint32_t *cnt, uint32_t dist, uint32_t tot,
|
||||
uint32_t cum, uint32_t *lo, uint32_t *hi,
|
||||
uint32_t *total) {
|
||||
*total = tot + dist;
|
||||
uint32_t acc = 0;
|
||||
for (int i = 0; i < 256; i++) {
|
||||
uint32_t f = cnt[i];
|
||||
if (cum < acc + f) { *lo = acc; *hi = acc + f; return i; }
|
||||
acc += f;
|
||||
}
|
||||
*lo = acc; *hi = acc + dist;
|
||||
return ESC;
|
||||
}
|
||||
|
||||
static int encode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
cnt2 = malloc((size_t)65536 * 256 * sizeof *cnt2);
|
||||
if (!cnt2) return 2;
|
||||
model_reset();
|
||||
bitw_t w;
|
||||
memset(&w, 0, sizeof w);
|
||||
enc_t e = { 0, 0xFFFFFFFFu, 0, &w };
|
||||
int p2 = 0, p1 = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
int b = in[i];
|
||||
uint32_t c2 = (uint32_t)((p2 << 8) | p1);
|
||||
uint32_t *row2 = cnt2 + (size_t)c2 * 256;
|
||||
uint32_t lo, hi, total;
|
||||
int done = 0;
|
||||
if (tot2[c2] > 0) {
|
||||
if (level_interval(row2, dist2[c2], tot2[c2], b, &lo, &hi, &total)) {
|
||||
enc_symbol(&e, lo, hi, total);
|
||||
done = 1;
|
||||
} else {
|
||||
level_interval(row2, dist2[c2], tot2[c2], ESC, &lo, &hi, &total);
|
||||
enc_symbol(&e, lo, hi, total);
|
||||
}
|
||||
}
|
||||
if (!done && tot1[p1] > 0) {
|
||||
if (level_interval(cnt1[p1], dist1[p1], tot1[p1], b, &lo, &hi, &total)) {
|
||||
enc_symbol(&e, lo, hi, total);
|
||||
done = 1;
|
||||
} else {
|
||||
level_interval(cnt1[p1], dist1[p1], tot1[p1], ESC, &lo, &hi, &total);
|
||||
enc_symbol(&e, lo, hi, total);
|
||||
}
|
||||
}
|
||||
if (!done && tot0 > 0) {
|
||||
if (level_interval(cnt0, dist0, tot0, b, &lo, &hi, &total)) {
|
||||
enc_symbol(&e, lo, hi, total);
|
||||
done = 1;
|
||||
} else {
|
||||
level_interval(cnt0, dist0, tot0, ESC, &lo, &hi, &total);
|
||||
enc_symbol(&e, lo, hi, total);
|
||||
}
|
||||
}
|
||||
if (!done) {
|
||||
/* order -1: uniform over 256 */
|
||||
enc_symbol(&e, (uint32_t)b, (uint32_t)b + 1, 256);
|
||||
}
|
||||
model_update(b, p2, p1);
|
||||
p2 = p1; p1 = b;
|
||||
}
|
||||
enc_flush(&e);
|
||||
size_t total_out = 8 + w.len;
|
||||
uint8_t *out = malloc(total_out ? total_out : 1);
|
||||
if (!out) return 2;
|
||||
memcpy(out, "PPM2", 4);
|
||||
out[4] = (uint8_t)(n & 0xff);
|
||||
out[5] = (uint8_t)((n >> 8) & 0xff);
|
||||
out[6] = (uint8_t)((n >> 16) & 0xff);
|
||||
out[7] = (uint8_t)((n >> 24) & 0xff);
|
||||
memcpy(out + 8, w.buf, w.len);
|
||||
spit(outpath, out, total_out);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int decode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
if (n < 8 || memcmp(in, "PPM2", 4) != 0) {
|
||||
fprintf(stderr, "ppm: bad magic/header\n");
|
||||
return 3;
|
||||
}
|
||||
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
|
||||
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
|
||||
cnt2 = malloc((size_t)65536 * 256 * sizeof *cnt2);
|
||||
if (!cnt2) return 2;
|
||||
model_reset();
|
||||
bitr_t br = { in + 8, n - 8, 0, 0, 0 };
|
||||
dec_t d;
|
||||
dec_init(&d, &br);
|
||||
uint8_t *out = malloc(orig ? orig : 1);
|
||||
if (!out) return 2;
|
||||
int p2 = 0, p1 = 0;
|
||||
for (uint32_t i = 0; i < orig; i++) {
|
||||
int b = -1;
|
||||
uint32_t c2 = (uint32_t)((p2 << 8) | p1);
|
||||
uint32_t *row2 = cnt2 + (size_t)c2 * 256;
|
||||
uint32_t lo, hi, total, cum;
|
||||
if (tot2[c2] > 0) {
|
||||
cum = dec_cum(&d, tot2[c2] + dist2[c2]);
|
||||
int s = level_lookup(row2, dist2[c2], tot2[c2], cum, &lo, &hi, &total);
|
||||
dec_update(&d, lo, hi, total);
|
||||
if (s != ESC) b = s;
|
||||
}
|
||||
if (b < 0 && tot1[p1] > 0) {
|
||||
cum = dec_cum(&d, tot1[p1] + dist1[p1]);
|
||||
int s = level_lookup(cnt1[p1], dist1[p1], tot1[p1], cum, &lo, &hi, &total);
|
||||
dec_update(&d, lo, hi, total);
|
||||
if (s != ESC) b = s;
|
||||
}
|
||||
if (b < 0 && tot0 > 0) {
|
||||
cum = dec_cum(&d, tot0 + dist0);
|
||||
int s = level_lookup(cnt0, dist0, tot0, cum, &lo, &hi, &total);
|
||||
dec_update(&d, lo, hi, total);
|
||||
if (s != ESC) b = s;
|
||||
}
|
||||
if (b < 0) {
|
||||
cum = dec_cum(&d, 256);
|
||||
b = (int)cum;
|
||||
dec_update(&d, cum, cum + 1, 256);
|
||||
}
|
||||
out[i] = (uint8_t)b;
|
||||
model_update(b, p2, p1);
|
||||
p2 = p1; p1 = b;
|
||||
}
|
||||
spit(outpath, out, orig);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
|
||||
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
|
||||
: decode(argv[2], argv[3]);
|
||||
}
|
||||
@@ -504,7 +504,6 @@ static int write_entries(FILE *f, entry_list_t *list, int level,
|
||||
h.orig_size = 0;
|
||||
h.stored_size = 0;
|
||||
h.blob_size = 0;
|
||||
h.crc16 = crc16_of(NULL, 0); /* empty blob: 0xFFFF */
|
||||
lzply_sha256((const uint8_t *)"", 0, h.sha);
|
||||
if (write_entry_header(f, &h) != 0)
|
||||
return -1;
|
||||
@@ -518,7 +517,7 @@ static int write_entries(FILE *f, entry_list_t *list, int level,
|
||||
}
|
||||
if (entry_encode(raw, raw_len, level, ecc,
|
||||
&stored, &stored_len, &blob_len, &poly_id, &is_bch,
|
||||
&eff_level, h.sha, &h.crc16) != 0) {
|
||||
&eff_level, h.sha) != 0) {
|
||||
fprintf(stderr, "%s: failed to encode %s\n", lzply_progname, e->full);
|
||||
free(raw);
|
||||
return -1;
|
||||
@@ -641,7 +640,7 @@ static int cmd_create(const char **inputs, int ninputs, const char *output_arg,
|
||||
rc = EXIT_IO;
|
||||
goto done;
|
||||
}
|
||||
/* The format is v5, always. */
|
||||
/* The format is v4, always. */
|
||||
f = fopen(out_path, "wb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot create %s: %s\n", lzply_progname, out_path,
|
||||
@@ -783,7 +782,7 @@ static int cmd_append(const char *archive, const char **inputs, int ninputs,
|
||||
for (j = 0; j < old.len; j++)
|
||||
if (replaced[j])
|
||||
nrep++;
|
||||
(void)old_version; /* the format is v5, always */
|
||||
(void)old_version; /* the format is v4, always */
|
||||
new_count = (uint32_t)(old.len - nrep + list.len);
|
||||
if (!has_dup) {
|
||||
/* True incremental append: stage the new entries to a temp
|
||||
@@ -1012,25 +1011,11 @@ static int open_archive(const char *path, FILE **f_out, uint32_t *count_out,
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
{
|
||||
int ver = 0;
|
||||
int ghr = read_global_header_full(f, &ver, count_out);
|
||||
if (ghr != 0) {
|
||||
if (ghr == -2 && ver == 4)
|
||||
fprintf(stderr, "%s: %s is an LZPL v4 archive, which "
|
||||
"predates the CRC16 migration (v5); re-create it "
|
||||
"with lzply -c -- it cannot be read by this version\n",
|
||||
lzply_progname, path);
|
||||
else if (ghr == -2)
|
||||
fprintf(stderr, "%s: %s is an LZPL archive of unsupported "
|
||||
"version %d (this version reads v%d only)\n",
|
||||
lzply_progname, path, ver, LZPLY_VERSION);
|
||||
else
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
if (read_global_header(f, count_out) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
*f_out = f;
|
||||
*size_out = st.st_size;
|
||||
@@ -1050,7 +1035,7 @@ static int cmd_list(const char *archive, const char **selectors, int nselectors,
|
||||
uint32_t seen = 0;
|
||||
if (rc != 0)
|
||||
return rc;
|
||||
printf("%-40s %12s %12s lvl ecc crc16\n", "path", "original", "stored");
|
||||
printf("%-40s %12s %12s lvl ecc\n", "path", "original", "stored");
|
||||
for (;;) {
|
||||
ehdr_t h;
|
||||
int r = read_entry_header(f, &h);
|
||||
@@ -1079,10 +1064,10 @@ static int cmd_list(const char *archive, const char **selectors, int nselectors,
|
||||
(unsigned)(h.rs_level | ((unsigned)h.reserved << 8)));
|
||||
else
|
||||
snprintf(ecc, sizeof ecc, "-");
|
||||
printf("%-40s %12s %12s %d %-8s %04x\n", h.path,
|
||||
printf("%-40s %12s %12s %d %-8s\n", h.path,
|
||||
human_size(h.orig_size, b1, sizeof b1),
|
||||
human_size(h.stored_size, b2, sizeof b2),
|
||||
h.level, ecc, (unsigned)h.crc16);
|
||||
h.level, ecc);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
@@ -1192,7 +1177,7 @@ static int cmd_extract(const char *archive, const char *dest_arg,
|
||||
int dr = entry_decode(stored, (size_t)h.stored_size, h.level,
|
||||
is_bch, poly_id,
|
||||
h.sha, (size_t)h.blob_size,
|
||||
&raw, &raw_len, &corrected, h.crc16);
|
||||
&raw, &raw_len, &corrected);
|
||||
free(stored);
|
||||
if (dr != 0) {
|
||||
fprintf(stderr, "%s: %s: corrupt or unrecoverable data\n",
|
||||
@@ -1278,9 +1263,9 @@ static int cmd_inspect(const char *archive, const char **selectors,
|
||||
uint32_t seen = 0, ndirs = 0, nfiles = 0;
|
||||
if (rc != 0)
|
||||
return rc;
|
||||
printf("%-40s %-10s %-4s %-11s %-20s %12s %12s %3s %-8s %6s\n",
|
||||
printf("%-40s %-10s %-4s %-11s %-20s %12s %12s %3s %-8s\n",
|
||||
"path", "type", "perm", "symbolic", "mtime (UTC)",
|
||||
"original", "stored", "lvl", "ecc", "crc16");
|
||||
"original", "stored", "lvl", "ecc");
|
||||
for (;;) {
|
||||
ehdr_t h;
|
||||
int r = read_entry_header(f, &h);
|
||||
@@ -1313,13 +1298,13 @@ static int cmd_inspect(const char *archive, const char **selectors,
|
||||
(unsigned)(h.rs_level | ((unsigned)h.reserved << 8)));
|
||||
else
|
||||
snprintf(ecc, sizeof ecc, "-");
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s %04x\n",
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s\n",
|
||||
h.path, is_dir ? "directory" : "file",
|
||||
(unsigned)(h.mode & 07777), perm, mt,
|
||||
human_size(h.orig_size, b1, sizeof b1),
|
||||
human_size(h.stored_size, b2, sizeof b2),
|
||||
(unsigned)h.level,
|
||||
ecc, (unsigned)h.crc16);
|
||||
ecc);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
|
||||
@@ -1,421 +0,0 @@
|
||||
/* lzply_deep_repair.c - repair entries past the BCH limit t.
|
||||
*
|
||||
* Usage:
|
||||
* lzply_deep_repair [-l max-level] [--time-budget seconds] [-v]
|
||||
* [-o outdir] [--entry name] archive
|
||||
*
|
||||
* Reads an LZPL v5 or LZRS v1 archive and attempts, per entry, the
|
||||
* escalating repair ladder from deep_repair.h (L0 standard decode
|
||||
* to t, L1 Chase-1 flips, L2 Chase-2 flips, L3 cross-block list
|
||||
* decoding), with the entry's CRC16 as the fast oracle and SHA-256
|
||||
* as the final oracle. Recovered entries are written under outdir
|
||||
* (default ./repaired), preserving their stored paths. Nothing is
|
||||
* ever written unless it passes both oracles.
|
||||
*
|
||||
* Per entry it reports the level the repair landed at and the
|
||||
* per-level timing -- the "time of arrival": how long each level
|
||||
* took, how many candidates were tried, how many the CRC rejected,
|
||||
* and how many bits were corrected. -v adds the per-level trial
|
||||
* counts (BM trials, splitting-filter passes, valid codewords).
|
||||
*
|
||||
* Exit codes: 0 all entries recovered, 1 usage, 2 I/O error,
|
||||
* 3 any entry unrecoverable (matching lzply's EXIT_CORRUPT).
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <getopt.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "deep_repair.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "lzrs_lib.h"
|
||||
|
||||
static const char *prog = "lzply_deep_repair";
|
||||
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr,
|
||||
"Usage: %s [-l max-level 0..3] [--time-budget seconds] [-v]\n"
|
||||
" [-o outdir] [--entry name] archive\n"
|
||||
" -l N highest repair level to attempt (default 3)\n"
|
||||
" --time-budget S wall-clock budget per entry, seconds (default %.0f)\n"
|
||||
" -v verbose: per-level trial counts\n"
|
||||
" -o DIR output directory for recovered files (default ./repaired)\n"
|
||||
" --entry NAME repair only the entry with this stored path\n"
|
||||
"Levels: L0 standard decode to t, L1 Chase-1 flips,\n"
|
||||
"L2 Chase-2 flips, L3 cross-block list decoding.\n",
|
||||
prog, DEEP_DEFAULT_BUDGET_SEC);
|
||||
}
|
||||
|
||||
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
|
||||
static int mkdir_p(const char *path, mode_t mode)
|
||||
{
|
||||
char *tmp = xstrdup(path);
|
||||
size_t n = strlen(tmp);
|
||||
size_t i;
|
||||
if (n == 0) {
|
||||
free(tmp);
|
||||
return 0;
|
||||
}
|
||||
while (n > 1 && tmp[n - 1] == '/')
|
||||
tmp[--n] = '\0';
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (tmp[i] == '/' || tmp[i] == '\0') {
|
||||
char save = tmp[i];
|
||||
struct stat st;
|
||||
tmp[i] = '\0';
|
||||
if (stat(tmp, &st) != 0) {
|
||||
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
|
||||
free(tmp);
|
||||
return -1;
|
||||
}
|
||||
} else if (!S_ISDIR(st.st_mode)) {
|
||||
free(tmp);
|
||||
return -1;
|
||||
}
|
||||
tmp[i] = save;
|
||||
}
|
||||
}
|
||||
free(tmp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int write_out_file(const char *path, const uint8_t *data, size_t len,
|
||||
uint32_t mode)
|
||||
{
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f)
|
||||
return -1;
|
||||
if (len > 0 && fwrite(data, 1, len, f) != len) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (fclose(f) != 0)
|
||||
return -1;
|
||||
if (mode)
|
||||
chmod(path, (mode_t)(mode & 07777));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int max_level = DEEP_MAX_LEVEL;
|
||||
double budget = DEEP_DEFAULT_BUDGET_SEC;
|
||||
int verbose = 0;
|
||||
const char *outdir = "./repaired";
|
||||
const char *only_entry = NULL;
|
||||
const char *archive = NULL;
|
||||
int is_lzrs = 0;
|
||||
FILE *f = NULL;
|
||||
uint8_t magic[4];
|
||||
int opt;
|
||||
static struct option long_opts[] = {
|
||||
{ "time-budget", required_argument, NULL, 1000 },
|
||||
{ "entry", required_argument, NULL, 1001 },
|
||||
{ "help", no_argument, NULL, 'h' },
|
||||
{ NULL, 0, NULL, 0 }
|
||||
};
|
||||
|
||||
lzply_set_progname(prog);
|
||||
while ((opt = getopt_long(argc, argv, "l:vo:h", long_opts, NULL)) != -1) {
|
||||
switch (opt) {
|
||||
case 'l':
|
||||
max_level = atoi(optarg);
|
||||
if (max_level < 0 || max_level > DEEP_MAX_LEVEL) {
|
||||
fprintf(stderr, "%s: level must be 0..%d\n",
|
||||
prog, DEEP_MAX_LEVEL);
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
break;
|
||||
case 'v':
|
||||
verbose = 1;
|
||||
break;
|
||||
case 'o':
|
||||
outdir = optarg;
|
||||
break;
|
||||
case 1000:
|
||||
budget = atof(optarg);
|
||||
if (budget <= 0) {
|
||||
fprintf(stderr, "%s: --time-budget must be > 0\n", prog);
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
break;
|
||||
case 1001:
|
||||
only_entry = optarg;
|
||||
break;
|
||||
case 'h':
|
||||
usage();
|
||||
return 0;
|
||||
default:
|
||||
usage();
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
}
|
||||
if (optind + 1 != argc) {
|
||||
usage();
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
archive = argv[optind];
|
||||
|
||||
f = fopen(archive, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
|
||||
strerror(errno));
|
||||
return EXIT_IO;
|
||||
}
|
||||
if (fread(magic, 1, 4, f) != 4) {
|
||||
fprintf(stderr, "%s: %s is too short to be an archive\n",
|
||||
prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
if (memcmp(magic, "LZRS", 4) == 0)
|
||||
is_lzrs = 1;
|
||||
else if (memcmp(magic, "LZPL", 4) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n",
|
||||
prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
/* Validate the archive up front (version, headers, end marker),
|
||||
* so a structurally broken archive fails before any repair is
|
||||
* attempted. The scan also gives the clear v4 message for old
|
||||
* LZPL archives. */
|
||||
{
|
||||
int version = 0;
|
||||
uint32_t count = 0;
|
||||
off_t size = 0, end_off = 0;
|
||||
scan_list_t entries;
|
||||
int s;
|
||||
rewind(f);
|
||||
if (is_lzrs)
|
||||
s = lzrs_scan_archive(archive, &version, &count, &size,
|
||||
&entries, &end_off);
|
||||
else
|
||||
s = scan_archive(archive, &version, &count, &size,
|
||||
&entries, &end_off);
|
||||
if (s != 0) {
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
scan_list_free(&entries);
|
||||
rewind(f);
|
||||
}
|
||||
if (mkdir_p(outdir, 0755) != 0) {
|
||||
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
|
||||
prog, outdir, strerror(errno));
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
|
||||
/* Skip the 16-byte global header; then walk the entries. */
|
||||
if (fseeko(f, 16, SEEK_SET) != 0) {
|
||||
fprintf(stderr, "%s: cannot seek in %s\n", prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
{
|
||||
int worst = 0;
|
||||
long n_ok = 0, n_fail = 0, n_dir = 0;
|
||||
long landed[4] = { 0, 0, 0, 0 };
|
||||
double t_start = bch_now();
|
||||
for (;;) {
|
||||
char *path = NULL;
|
||||
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
|
||||
uint16_t poly_id = 0, want_crc16 = 0;
|
||||
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
|
||||
uint32_t mode = 0;
|
||||
uint8_t sha[32];
|
||||
uint8_t *stored = NULL;
|
||||
int r;
|
||||
if (is_lzrs) {
|
||||
lzrs_ehdr_t h;
|
||||
r = lzrs_read_entry_header(f, &h);
|
||||
if (r == 1)
|
||||
break;
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: truncated or corrupt entry header\n",
|
||||
prog);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
path = h.path;
|
||||
level = h.level;
|
||||
is_bch = (h.flags & FLAG_BCH) != 0;
|
||||
rs_level = h.rs_level;
|
||||
is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
poly_id = h.bch_poly_id;
|
||||
want_crc16 = h.crc16;
|
||||
stored_size = h.stored_size;
|
||||
blob_size = h.blob_size;
|
||||
orig_size = h.orig_size;
|
||||
mode = h.mode;
|
||||
memcpy(sha, h.sha, 32);
|
||||
} else {
|
||||
ehdr_t h;
|
||||
r = read_entry_header(f, &h);
|
||||
if (r == 1)
|
||||
break;
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: truncated or corrupt entry header\n",
|
||||
prog);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
path = h.path;
|
||||
level = h.level;
|
||||
is_bch = (h.flags & FLAG_BCH) != 0;
|
||||
rs_level = 0;
|
||||
is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
poly_id = (uint16_t)(h.rs_level |
|
||||
((uint16_t)h.reserved << 8));
|
||||
want_crc16 = h.crc16;
|
||||
stored_size = h.stored_size;
|
||||
blob_size = h.blob_size;
|
||||
orig_size = h.orig_size;
|
||||
mode = h.mode;
|
||||
memcpy(sha, h.sha, 32);
|
||||
}
|
||||
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
|
||||
if (stored_size > 0 &&
|
||||
fread(stored, 1, (size_t)stored_size, f) !=
|
||||
(size_t)stored_size) {
|
||||
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
|
||||
free(stored);
|
||||
free(path);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
if (only_entry && strcmp(path, only_entry) != 0) {
|
||||
free(stored);
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
if (is_dir) {
|
||||
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
|
||||
sprintf(dp, "%s/%s", outdir, path);
|
||||
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
|
||||
fprintf(stderr, "%s: cannot create directory %s: %s\n",
|
||||
prog, dp, strerror(errno));
|
||||
free(dp);
|
||||
free(stored);
|
||||
free(path);
|
||||
n_dir++;
|
||||
continue;
|
||||
}
|
||||
{
|
||||
uint8_t *raw = NULL;
|
||||
size_t raw_len = 0;
|
||||
deep_stats_t st;
|
||||
int drc = deep_repair_entry(stored, (size_t)stored_size,
|
||||
level, is_bch, poly_id,
|
||||
rs_level, sha,
|
||||
(size_t)blob_size, want_crc16,
|
||||
max_level, budget,
|
||||
&raw, &raw_len, &st);
|
||||
free(stored);
|
||||
if (drc != 0) {
|
||||
printf("%s: FAILED (stage %s) after %.3fs, "
|
||||
"cands %ld crc-rejects %ld sha-rejects %ld\n",
|
||||
path, st.fail_stage, st.t_total,
|
||||
st.cands_tried, st.crc_rejects, st.sha_rejects);
|
||||
if (verbose) {
|
||||
int lv;
|
||||
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
|
||||
printf(" L%d: %.3fs trials %ld split %ld "
|
||||
"codewords %ld\n", lv, st.t_level[lv],
|
||||
st.trials[lv], st.split_pass[lv],
|
||||
st.codewords[lv]);
|
||||
printf(" blocks %ld/%ld failed%s\n",
|
||||
st.blocks_failed, st.blocks_total,
|
||||
st.partial ? " (partial: budget hit)" : "");
|
||||
}
|
||||
n_fail++;
|
||||
if (EXIT_CORRUPT > worst)
|
||||
worst = EXIT_CORRUPT;
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
if (raw_len != orig_size) {
|
||||
fprintf(stderr, "%s: %s: size mismatch after repair "
|
||||
"(got %zu, expected %llu)\n", prog, path,
|
||||
raw_len, (unsigned long long)orig_size);
|
||||
free(raw);
|
||||
free(path);
|
||||
n_fail++;
|
||||
if (EXIT_CORRUPT > worst)
|
||||
worst = EXIT_CORRUPT;
|
||||
continue;
|
||||
}
|
||||
{
|
||||
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
|
||||
char *pd;
|
||||
sprintf(dp, "%s/%s", outdir, path);
|
||||
pd = parent_dir(dp);
|
||||
if (mkdir_p(pd, 0755) != 0)
|
||||
fprintf(stderr, "%s: cannot create %s: %s\n",
|
||||
prog, pd, strerror(errno));
|
||||
free(pd);
|
||||
if (write_out_file(dp, raw, raw_len, mode) != 0) {
|
||||
fprintf(stderr, "%s: cannot write %s: %s\n",
|
||||
prog, dp, strerror(errno));
|
||||
if (EXIT_IO > worst)
|
||||
worst = EXIT_IO;
|
||||
free(dp);
|
||||
free(raw);
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
free(dp);
|
||||
}
|
||||
{
|
||||
char rssuf[48];
|
||||
rssuf[0] = '\0';
|
||||
if (st.rs_corrected > 0)
|
||||
snprintf(rssuf, sizeof rssuf,
|
||||
" (RS corrected %d symbols)",
|
||||
st.rs_corrected);
|
||||
printf("%s: RECOVERED at L%d in %.3fs "
|
||||
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
|
||||
"cands %ld crc-rejects %ld sha-rejects %ld "
|
||||
"bch-corrected %d%s\n",
|
||||
path, st.level_landed, st.t_total,
|
||||
st.t_level[0], st.t_level[1], st.t_level[2],
|
||||
st.t_level[3], st.cands_tried, st.crc_rejects,
|
||||
st.sha_rejects, st.bch_corrected, rssuf);
|
||||
}
|
||||
if (verbose) {
|
||||
int lv;
|
||||
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
|
||||
printf(" L%d: %.3fs trials %ld split %ld "
|
||||
"codewords %ld\n", lv, st.t_level[lv],
|
||||
st.trials[lv], st.split_pass[lv],
|
||||
st.codewords[lv]);
|
||||
printf(" blocks %ld/%ld failed%s\n",
|
||||
st.blocks_failed, st.blocks_total,
|
||||
st.partial ? " (partial: budget hit)" : "");
|
||||
}
|
||||
landed[st.level_landed]++;
|
||||
n_ok++;
|
||||
free(raw);
|
||||
free(path);
|
||||
}
|
||||
}
|
||||
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
|
||||
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
|
||||
n_ok, landed[0], landed[1], landed[2], landed[3],
|
||||
n_fail, n_dir, bch_now() - t_start);
|
||||
fclose(f);
|
||||
return worst;
|
||||
}
|
||||
}
|
||||
+51
-168
@@ -8,20 +8,19 @@
|
||||
* format. (v3 archives are rejected outright; the format changed
|
||||
* in v4.)
|
||||
*
|
||||
* Archive format v5 (all integers little-endian):
|
||||
* Archive format v4 (all integers little-endian):
|
||||
* global header (16 bytes):
|
||||
* magic "LZPL", version u8 (=5), flags u8, entry_count u32,
|
||||
* magic "LZPL", version u8 (=4), flags u8, entry_count u32,
|
||||
* reserved u64
|
||||
* entries, each:
|
||||
* u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
* u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
* u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
* u32 mode, u64 mtime, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 76 bytes before it; blob_size is the
|
||||
* (header_crc32 covers the 74 bytes before it; blob_size is the
|
||||
* length of the compressed stream before error-correction parity
|
||||
* was added; mtime is the source file's modification time,
|
||||
* seconds since the epoch, UTC; crc16 is CRC-16/CCITT-FALSE of
|
||||
* the blob)
|
||||
* seconds since the epoch, UTC)
|
||||
* end marker: u16 path_len == 0
|
||||
* Flags: bit 0 is unused (it was used by v3), bit 1 =
|
||||
* directory, bit 2 = BCH mode.
|
||||
@@ -164,39 +163,6 @@ uint32_t crc32_of(const uint8_t *p, size_t n){
|
||||
return c ^ 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
/* CRC-16/CCITT-FALSE (polynomial 0x1021, init 0xFFFF, refin=false,
|
||||
* refout=false, xorout 0x0000). Check value: crc16_of("123456789")
|
||||
* == 0x29B1; crc16_of(NULL, 0) == 0xFFFF. Table-driven, same shape
|
||||
* as the CRC-32 above. */
|
||||
static uint16_t crc16_table[256];
|
||||
|
||||
static int crc16_ready = 0;
|
||||
|
||||
void crc16_init(void)
|
||||
{
|
||||
uint16_t i;
|
||||
int j;
|
||||
for (i = 0; i < 256; i++) {
|
||||
uint16_t c = (uint16_t)(i << 8);
|
||||
for (j = 0; j < 8; j++)
|
||||
c = (c & 0x8000u) ? (uint16_t)((c << 1) ^ 0x1021u)
|
||||
: (uint16_t)(c << 1);
|
||||
crc16_table[i] = c;
|
||||
}
|
||||
crc16_ready = 1;
|
||||
}
|
||||
|
||||
uint16_t crc16_of(const uint8_t *p, size_t n){
|
||||
uint16_t c = 0xFFFFu;
|
||||
size_t i;
|
||||
if (!crc16_ready)
|
||||
crc16_init();
|
||||
for (i = 0; i < n; i++)
|
||||
c = (uint16_t)((c << 8) ^
|
||||
crc16_table[((c >> 8) ^ p[i]) & 0xff]);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* Dictionary size / match-length limit per level, matching the lzip
|
||||
* command-line tool's own table (verified by comparing output with
|
||||
* `lzip -N` on the same input). */
|
||||
@@ -365,7 +331,7 @@ int entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32], uint16_t *crc16_out)
|
||||
uint8_t sha_out[32])
|
||||
{
|
||||
uint8_t *comp = NULL, *blob = NULL, *ecout = NULL;
|
||||
size_t comp_len = 0, blob_len = 0, ec_len = 0;
|
||||
@@ -411,12 +377,6 @@ int entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
/* The CRC16 covers the blob (the pre-ECC stream). Compute it now:
|
||||
* the blob is freed inside the BCH branch below (or handed to the
|
||||
* caller as the stored bytes when there is no BCH layer), so this
|
||||
* is the last point where it is uniformly available. */
|
||||
if (crc16_out)
|
||||
*crc16_out = crc16_of(blob, blob_len);
|
||||
if (poly) {
|
||||
ec_len = bch_encoded_len(blob_len, poly);
|
||||
ecout = xmalloc(ec_len ? ec_len : 1);
|
||||
@@ -468,72 +428,35 @@ static uint8_t *blob_to_raw_checked(const uint8_t *blob, size_t blob_len,
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
|
||||
* CRC16 mismatch, SHA-256 mismatch). `corrected` receives the number
|
||||
* of bit errors corrected (BCH). `is_bch` / `poly_id` come from the
|
||||
* entry header; a non-BCH entry has no error correction. A level-0
|
||||
* entry is stored uncompressed: the blob is copied verbatim, no
|
||||
* lzip decode.
|
||||
*
|
||||
* CRC16 gate: the decoded blob is checked against want_crc16 (the
|
||||
* entry header's CRC16) BEFORE decompression, in every path. A
|
||||
* mismatch is a clean failure, never a misdecode, and a specific
|
||||
* message is printed (stored 0000 means the archive predates the
|
||||
* CRC16 migration, or the data is corrupt).
|
||||
* SHA-256 mismatch). `corrected` receives the number of bit errors
|
||||
* corrected (BCH). `is_bch` / `poly_id` come from the entry header;
|
||||
* a non-BCH entry has no error correction. A level-0 entry is stored
|
||||
* uncompressed: the blob is copied verbatim, no lzip decode.
|
||||
*
|
||||
* Two-pass silent repair (BCH entries only):
|
||||
* Pass 1 (fast path, unchanged): standard BCH decode, then CRC,
|
||||
* decompress + SHA-256. If all pass, return immediately. No extra
|
||||
* cost in the common case.
|
||||
* Pass 2 (recovery, only when pass 1 fails): the CRC/hash failure
|
||||
* means the decoder miscorrected or could not correct. Try
|
||||
* alternative BCH decodings (bch_decode_candidates); each
|
||||
* candidate is CRC-checked first (cheap: no decompression) and
|
||||
* only CRC-passing candidates go to decompress + SHA-256. Accept
|
||||
* the FIRST candidate whose decompressed output hashes correctly.
|
||||
* If none passes, return -1 (loud failure). No data is ever
|
||||
* returned unless it passes the CRC16 and SHA-256 checks, in
|
||||
* either pass -- a silent failure (wrong data returned as if
|
||||
* correct) is impossible by construction.
|
||||
* Pass 1 (fast path, unchanged): standard BCH decode, then
|
||||
* decompress + SHA-256. If the hash passes, return immediately.
|
||||
* No extra cost in the common case.
|
||||
* Pass 2 (recovery, only when pass 1 fails): the hash failure means
|
||||
* the decoder miscorrected or could not correct. Try alternative
|
||||
* BCH decodings (bch_decode_candidates) and accept the FIRST
|
||||
* candidate whose decompressed output hashes correctly. If none
|
||||
* passes, return -1 (loud failure). No data is ever returned unless
|
||||
* it passes the SHA-256 check, in either pass -- a silent failure
|
||||
* (wrong data returned as if correct) is impossible by construction.
|
||||
*/
|
||||
|
||||
/* Print the specific CRC16 failure message once decoding has
|
||||
* definitively failed. Stored 0000 is the pre-migration marker
|
||||
* (writers before the CRC16 migration stored 0), so say so; any
|
||||
* other mismatch is corruption. Called once per failed entry, not
|
||||
* once per candidate. */
|
||||
static void crc_fail_report(uint16_t want, uint16_t got)
|
||||
{
|
||||
if (want == 0)
|
||||
fprintf(stderr, "%s: entry CRC16 is 0000 but the decoded blob "
|
||||
"computes to %04x: this archive predates the CRC16 "
|
||||
"migration, or the data is corrupt; re-create it\n",
|
||||
lzply_progname, (unsigned)got);
|
||||
else
|
||||
fprintf(stderr, "%s: entry CRC16 mismatch (stored %04x, "
|
||||
"computed %04x): data corrupt\n",
|
||||
lzply_progname, (unsigned)want, (unsigned)got);
|
||||
}
|
||||
|
||||
int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint8_t **raw, size_t *raw_len, int *corrected,
|
||||
uint16_t want_crc16)
|
||||
uint8_t **raw, size_t *raw_len, int *corrected)
|
||||
{
|
||||
*corrected = 0;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (!is_bch) {
|
||||
/* No error correction: the stored data is the blob itself.
|
||||
* CRC-check it before decompressing anything. */
|
||||
uint16_t got;
|
||||
/* No error correction: the stored data is the blob itself. */
|
||||
if (stored_len != blob_size)
|
||||
return -1;
|
||||
got = crc16_of(stored, stored_len);
|
||||
if (got != want_crc16) {
|
||||
crc_fail_report(want_crc16, got);
|
||||
return -1;
|
||||
}
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(stored, stored_len, level,
|
||||
want_sha, &out_len);
|
||||
@@ -548,32 +471,22 @@ int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
return -1;
|
||||
uint8_t *blob = xmalloc(blob_size ? blob_size : 1);
|
||||
int corr = 0;
|
||||
/* Set when any CRC comparison ran, with the last computed value,
|
||||
* so the failure message can name the computed CRC. */
|
||||
int crc_checked = 0;
|
||||
uint16_t last_computed = 0;
|
||||
/* Pass 1: standard BCH decode, then CRC + decompress + hash. */
|
||||
/* Pass 1: standard BCH decode, then decompress + hash. */
|
||||
if (bch_decode(stored, stored_len, blob_size, poly, blob, &corr) == 0) {
|
||||
*corrected = corr;
|
||||
last_computed = crc16_of(blob, blob_size);
|
||||
crc_checked = 1;
|
||||
if (last_computed == want_crc16) {
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(blob, blob_size, level,
|
||||
want_sha, &out_len);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
free(blob);
|
||||
return 0;
|
||||
}
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(blob, blob_size, level,
|
||||
want_sha, &out_len);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
free(blob);
|
||||
return 0;
|
||||
}
|
||||
/* Pass-1 blob failed CRC / decompress / hash: fall through
|
||||
* to pass 2. */
|
||||
/* Pass-1 blob failed decompress/hash: fall through to pass 2. */
|
||||
}
|
||||
/* Pass 2: try alternative BCH decodings; CRC-check each candidate
|
||||
* first (cheap) and accept the first whose decompressed output
|
||||
* hashes correctly. */
|
||||
/* Pass 2: try alternative BCH decodings; accept the first whose
|
||||
* decompressed output hashes correctly. */
|
||||
{
|
||||
size_t candsize = blob_size ? blob_size : 1;
|
||||
uint8_t *cands = malloc((size_t)BCH_PASS2_MAX_CANDS * candsize);
|
||||
@@ -584,15 +497,10 @@ int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int nc = bch_decode_candidates(stored, stored_len, blob_size, poly,
|
||||
cands, BCH_PASS2_MAX_CANDS);
|
||||
for (int i = 0; i < nc; i++) {
|
||||
const uint8_t *cand = cands + (size_t)i * candsize;
|
||||
size_t out_len = 0;
|
||||
uint8_t *out;
|
||||
last_computed = crc16_of(cand, blob_size);
|
||||
crc_checked = 1;
|
||||
if (last_computed != want_crc16)
|
||||
continue; /* CRC rejects this candidate: cheap */
|
||||
out = blob_to_raw_checked(cand, blob_size, level,
|
||||
want_sha, &out_len);
|
||||
uint8_t *out = blob_to_raw_checked(cands + (size_t)i * candsize,
|
||||
blob_size, level,
|
||||
want_sha, &out_len);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
@@ -604,8 +512,6 @@ int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
free(cands);
|
||||
}
|
||||
free(blob);
|
||||
if (crc_checked)
|
||||
crc_fail_report(want_crc16, last_computed);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -626,8 +532,7 @@ char *parent_dir(const char *path){
|
||||
|
||||
/* rs_level + reserved: for a BCH entry (flags & FLAG_BCH) this is the
|
||||
* poly id, poly_id = rs_level | (reserved << 8). For an entry with
|
||||
* no error correction both are 0. crc16 is CRC-16/CCITT-FALSE of the
|
||||
* blob (0xFFFF for a directory entry, whose blob is empty). */
|
||||
* no error correction both are 0. */
|
||||
|
||||
int write_entry_header(FILE *f, const ehdr_t *h){
|
||||
uint8_t buf[LZPLY_EHDR_SIZE];
|
||||
@@ -646,8 +551,7 @@ int write_entry_header(FILE *f, const ehdr_t *h){
|
||||
memcpy(buf + 30, h->sha, 32);
|
||||
put32le(buf + 62, h->mode);
|
||||
put64le(buf + 66, h->mtime);
|
||||
put16le(buf + 74, h->crc16);
|
||||
put32le(buf + 76, crc32_of(buf, 76));
|
||||
put32le(buf + 74, crc32_of(buf, 74));
|
||||
if (fwrite(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (plen > 0 && fwrite(h->path, 1, plen, f) != plen)
|
||||
@@ -668,10 +572,10 @@ int read_entry_header(FILE *f, ehdr_t *h){
|
||||
return 1;
|
||||
if (fread(buf + 2, 1, LZPLY_EHDR_SIZE - 2, f) != LZPLY_EHDR_SIZE - 2)
|
||||
return -1;
|
||||
want_crc = get32le(buf + 76);
|
||||
put32le(buf + 76, 0);
|
||||
got_crc = crc32_of(buf, 76);
|
||||
put32le(buf + 76, want_crc);
|
||||
want_crc = get32le(buf + 74);
|
||||
put32le(buf + 74, 0);
|
||||
got_crc = crc32_of(buf, 74);
|
||||
put32le(buf + 74, want_crc);
|
||||
if (got_crc != want_crc)
|
||||
return -1;
|
||||
h->level = buf[2];
|
||||
@@ -684,7 +588,6 @@ int read_entry_header(FILE *f, ehdr_t *h){
|
||||
memcpy(h->sha, buf + 30, 32);
|
||||
h->mode = get32le(buf + 62);
|
||||
h->mtime = get64le(buf + 66);
|
||||
h->crc16 = get16le(buf + 74);
|
||||
if (h->level > 9)
|
||||
return -1;
|
||||
if (h->flags & FLAG_BCH) {
|
||||
@@ -716,10 +619,8 @@ int read_global_header(FILE *f, uint32_t *count_out){
|
||||
uint8_t buf[LZPLY_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0)
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0 || buf[4] != LZPLY_VERSION)
|
||||
return -1;
|
||||
if (buf[4] != LZPLY_VERSION)
|
||||
return -2; /* right magic, wrong version (e.g. v4) */
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
@@ -895,20 +796,15 @@ void scan_list_free(scan_list_t *l){
|
||||
}
|
||||
|
||||
/* Read the 16-byte global header, returning version and count.
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive,
|
||||
* -2 if the magic is right but the version is wrong. On -2
|
||||
* *version_out still holds the version byte found, so the caller
|
||||
* can name it. */
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive. */
|
||||
int read_global_header_full(FILE *f, int *version_out, uint32_t *count_out)
|
||||
{
|
||||
uint8_t buf[LZPLY_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0)
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0 || buf[4] != LZPLY_VERSION)
|
||||
return -1;
|
||||
*version_out = buf[4];
|
||||
if (buf[4] != LZPLY_VERSION)
|
||||
return -2;
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
@@ -936,24 +832,11 @@ int scan_archive(const char *path, int *version_out, uint
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
int ghr = read_global_header_full(f, version_out, count_out);
|
||||
if (ghr != 0) {
|
||||
if (ghr == -2 && *version_out == 4)
|
||||
fprintf(stderr, "%s: %s is an LZPL v4 archive, which "
|
||||
"predates the CRC16 migration (v5); re-create it "
|
||||
"with lzply -c -- it cannot be read by this version\n",
|
||||
lzply_progname, path);
|
||||
else if (ghr == -2)
|
||||
fprintf(stderr, "%s: %s is an LZPL archive of unsupported "
|
||||
"version %d (this version reads v%d only)\n",
|
||||
lzply_progname, path, *version_out, LZPLY_VERSION);
|
||||
else
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (read_global_header_full(f, version_out, count_out) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
memset(entries, 0, sizeof *entries);
|
||||
for (;;) {
|
||||
|
||||
+27
-66
@@ -1,28 +1,26 @@
|
||||
/* lzply_lib.h - shared core of the lzply archiver and lzply_mount.
|
||||
*
|
||||
* Everything both programs need: the v5 archive format, the per-entry
|
||||
* Everything both programs need: the v4 archive format, the per-entry
|
||||
* pipeline (lzip compress -> BCH encode, and the reverse), the header
|
||||
* I/O, the archive scan, and the date / selector filters. The
|
||||
* command-line tool (lzply.c) and the FUSE filesystem (lzply_mount.c)
|
||||
* both link lzply_lib.c. There is no legacy support: v5 is the only
|
||||
* format. (v4 archives are rejected outright with a message telling
|
||||
* the user to re-create them; the format changed in v5 to add the
|
||||
* per-entry CRC16.)
|
||||
* both link lzply_lib.c. There is no legacy support: v4 is the only
|
||||
* format. (v3 archives are rejected outright; the format changed
|
||||
* in v4.)
|
||||
*
|
||||
* Archive format v5 (all integers little-endian):
|
||||
* Archive format v4 (all integers little-endian):
|
||||
* global header (16 bytes):
|
||||
* magic "LZPL", version u8 (=5), flags u8, entry_count u32,
|
||||
* magic "LZPL", version u8 (=4), flags u8, entry_count u32,
|
||||
* reserved u64
|
||||
* entries, each:
|
||||
* u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
* u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
* u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
* u32 mode, u64 mtime, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 76 bytes before it; blob_size is the
|
||||
* (header_crc32 covers the 74 bytes before it; blob_size is the
|
||||
* length of the compressed stream before error-correction parity
|
||||
* was added; mtime is the source file's modification time,
|
||||
* seconds since the epoch, UTC; crc16 is CRC-16/CCITT-FALSE of
|
||||
* the blob -- see below)
|
||||
* seconds since the epoch, UTC)
|
||||
* end marker: u16 path_len == 0
|
||||
* Level is the lzip level (1..9) of the blob, or 0 for a stored
|
||||
* (uncompressed) entry: when the compressed blob would be no smaller
|
||||
@@ -32,21 +30,6 @@
|
||||
* Flags: bit 0 is unused (it was used by v3), bit 1 =
|
||||
* directory, bit 2 = BCH mode. Bit 0 is deliberately not renumbered.
|
||||
* For a BCH entry, poly_id = rs_level | (reserved << 8).
|
||||
*
|
||||
* CRC16 (v5; also LZRS v1, which has the same field): crc16 is
|
||||
* CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflection,
|
||||
* xorout 0; check value crc16_of("123456789") == 0x29B1) of the
|
||||
* blob -- the compressed stream before BCH/RS parity was added
|
||||
* (for a stored entry the blob is the raw bytes; for a directory
|
||||
* entry the blob is empty, so crc16 == 0xFFFF). Writers compute and
|
||||
* store it; readers verify it after error-correction decoding and
|
||||
* before decompression. A mismatch is a clean failure, never a
|
||||
* misdecode: the SHA-256 check remains the final oracle. The CRC16
|
||||
* is also the fast oracle for deep repair (docs/deep-repair.md):
|
||||
* candidate blobs are CRC-checked before the expensive
|
||||
* decompress + SHA-256 step, so most wrong candidates are rejected
|
||||
* cheaply. Expected residual false-accept is ~2^-16 per candidate
|
||||
* at the CRC stage (the SHA-256 stage then gates acceptance).
|
||||
*/
|
||||
#ifndef LZPLY_LIB_H
|
||||
#define LZPLY_LIB_H
|
||||
@@ -59,9 +42,9 @@
|
||||
#include "sha256.h"
|
||||
|
||||
#define LZPLY_MAGIC "LZPL"
|
||||
#define LZPLY_VERSION 5 /* the only format version */
|
||||
#define LZPLY_VERSION 4 /* the only format version */
|
||||
#define LZPLY_HDR_SIZE 16
|
||||
#define LZPLY_EHDR_SIZE 80
|
||||
#define LZPLY_EHDR_SIZE 78
|
||||
#define LZPLY_END_MARKER 0
|
||||
|
||||
#define FLAG_ISDIR 0x02
|
||||
@@ -107,13 +90,6 @@ uint64_t get64le(const uint8_t *p);
|
||||
void crc32_init(void);
|
||||
uint32_t crc32_of(const uint8_t *p, size_t n);
|
||||
|
||||
/* CRC-16/CCITT-FALSE (polynomial 0x1021, init 0xFFFF, no reflection,
|
||||
* xorout 0x0000). Check value: crc16_of("123456789", 9) == 0x29B1;
|
||||
* crc16_of(NULL, 0) == 0xFFFF (the value stored for directory
|
||||
* entries, whose blob is empty). */
|
||||
void crc16_init(void);
|
||||
uint16_t crc16_of(const uint8_t *p, size_t n);
|
||||
|
||||
/* Parent directory of path (everything before the last '/'; "." if
|
||||
* none). */
|
||||
char *parent_dir(const char *path);
|
||||
@@ -139,39 +115,30 @@ typedef struct {
|
||||
} ecc_opt_t;
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes.
|
||||
* Fills sha_out with SHA-256 of the raw bytes, and (when crc16_out
|
||||
* is non-NULL) *crc16_out with CRC-16/CCITT-FALSE of the blob (the
|
||||
* compressed stream before BCH parity; for a stored entry, the raw
|
||||
* bytes). *poly_id_out / *is_bch_out describe the error correction
|
||||
* actually used, for the entry header. *level_out is the level
|
||||
* actually stored: the requested level, or 0 when the entry is
|
||||
* stored uncompressed (level 0 requested, or the compressed blob
|
||||
* was no smaller than the original). BCH applies to the stored blob
|
||||
* either way.
|
||||
* Fills sha_out with SHA-256 of the raw bytes. *poly_id_out /
|
||||
* *is_bch_out describe the error correction actually used, for the
|
||||
* entry header. *level_out is the level actually stored: the
|
||||
* requested level, or 0 when the entry is stored uncompressed
|
||||
* (level 0 requested, or the compressed blob was no smaller than
|
||||
* the original). BCH applies to the stored blob either way.
|
||||
* Returns 0 on success. */
|
||||
int entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
const ecc_opt_t *ecc,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32], uint16_t *crc16_out);
|
||||
uint8_t sha_out[32]);
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
|
||||
* CRC16 mismatch, SHA-256 mismatch). `corrected` receives the number
|
||||
* of bit errors corrected (BCH). `is_bch` / `poly_id` come from the
|
||||
* entry header; a non-BCH entry has no error correction. A level-0
|
||||
* entry is stored uncompressed: the blob is copied verbatim, no
|
||||
* lzip decode. `want_crc16` is the CRC16 from the entry header: the
|
||||
* decoded blob is CRC-checked against it before decompression, so
|
||||
* a blob that fails the CRC is never decompressed or returned. A
|
||||
* mismatch prints a specific message (stored 0000 means the archive
|
||||
* predates the CRC16 migration, or the data is corrupt). */
|
||||
* SHA-256 mismatch). `corrected` receives the number of bit errors
|
||||
* corrected (BCH). `is_bch` / `poly_id` come from the entry header;
|
||||
* a non-BCH entry has no error correction. A level-0 entry is stored
|
||||
* uncompressed: the blob is copied verbatim, no lzip decode. */
|
||||
int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint8_t **raw, size_t *raw_len, int *corrected,
|
||||
uint16_t want_crc16);
|
||||
uint8_t **raw, size_t *raw_len, int *corrected);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Archive header I/O */
|
||||
@@ -184,12 +151,10 @@ typedef struct {
|
||||
uint8_t sha[32];
|
||||
uint32_t mode;
|
||||
uint64_t mtime; /* source mtime, seconds since epoch (UTC) */
|
||||
uint16_t crc16; /* CRC-16/CCITT-FALSE of the blob */
|
||||
} ehdr_t;
|
||||
/* rs_level + reserved: for a BCH entry (flags & FLAG_BCH) this is the
|
||||
* poly id, poly_id = rs_level | (reserved << 8). For an entry with
|
||||
* no error correction both are 0. crc16 covers the blob (see above);
|
||||
* for a directory entry (empty blob) it is 0xFFFF. */
|
||||
* no error correction both are 0. */
|
||||
|
||||
int write_entry_header(FILE *f, const ehdr_t *h);
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
@@ -197,11 +162,7 @@ int read_entry_header(FILE *f, ehdr_t *h);
|
||||
int read_global_header(FILE *f, uint32_t *count_out);
|
||||
void write_global_header(FILE *f, uint32_t count, int version);
|
||||
/* Read the 16-byte global header, returning version and count.
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive,
|
||||
* -2 if the magic is right but the version is wrong (e.g. a v4
|
||||
* archive, which predates the CRC16 migration). On -2 *version_out
|
||||
* still holds the version byte found, so the caller can say which
|
||||
* version it was. */
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive. */
|
||||
int read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out);
|
||||
|
||||
@@ -252,8 +213,8 @@ void fmt_perm(int is_dir, uint32_t mode, char *buf);
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* One entry found by scanning an archive: its stored path, its file
|
||||
* offset (start of the 80-byte header), and its total on-disk length
|
||||
* (80 + path_len + stored_size). */
|
||||
* offset (start of the 78-byte header), and its total on-disk length
|
||||
* (78 + path_len + stored_size). */
|
||||
typedef struct {
|
||||
char *path;
|
||||
off_t offset;
|
||||
|
||||
+2
-4
@@ -411,8 +411,7 @@ static int load_content(lzply_mount_state_t *st, fs_node_t *n)
|
||||
poly_id = (uint16_t)(n->hdr.rs_level | ((uint16_t)n->hdr.reserved << 8));
|
||||
rc = entry_decode(stored, (size_t)n->hdr.stored_size, n->hdr.level,
|
||||
is_bch, poly_id, n->hdr.sha,
|
||||
(size_t)n->hdr.blob_size, &raw, &raw_len, &corrected,
|
||||
n->hdr.crc16);
|
||||
(size_t)n->hdr.blob_size, &raw, &raw_len, &corrected);
|
||||
free(stored);
|
||||
if (rc != 0)
|
||||
return -EIO; /* corrupt: BCH uncorrectable / SHA mismatch */
|
||||
@@ -539,7 +538,6 @@ static int repack_archive(lzply_mount_state_t *st)
|
||||
h.orig_size = 0;
|
||||
h.stored_size = 0;
|
||||
h.blob_size = 0;
|
||||
h.crc16 = crc16_of(NULL, 0); /* empty blob: 0xFFFF */
|
||||
lzply_sha256((const uint8_t *)"", 0, h.sha);
|
||||
entry_off = ftello(out);
|
||||
if (write_entry_header(out, &h) != 0) {
|
||||
@@ -582,7 +580,7 @@ static int repack_archive(lzply_mount_state_t *st)
|
||||
if (entry_encode(n->content, n->content_len, st->level,
|
||||
&st->ecc,
|
||||
&stored, &stored_len, &blob_len, &poly_id,
|
||||
&is_bch, &eff_level, h.sha, &h.crc16) != 0)
|
||||
&is_bch, &eff_level, h.sha) != 0)
|
||||
goto fail;
|
||||
h.level = (uint8_t)eff_level; /* 0 when stored uncompressed */
|
||||
}
|
||||
|
||||
-349
@@ -1,349 +0,0 @@
|
||||
/* lzrs_lib.c - LZRS v1 archive format and per-entry pipeline.
|
||||
*
|
||||
* The entry pipeline is lzply v4 with one more layer on the
|
||||
* outside: raw -> lzip compress (or store) -> BCH encode -> RS
|
||||
* encode. RS is the outer layer because it corrects whole-byte
|
||||
* and burst errors, which is what a damaged block looks like
|
||||
* after the inner layers have done their work; BCH stays
|
||||
* responsible for scattered bit errors. Decode runs the layers
|
||||
* in reverse (RS, then BCH with its two-pass hash-gated repair,
|
||||
* then lzip), and the SHA-256 check at the end is the oracle for
|
||||
* the whole stack: no data is returned unless it hashes.
|
||||
*
|
||||
* Format: see lzrs_lib.h. The entry header is the v5 80-byte
|
||||
* layout plus bch_poly_id before the header CRC, which covers the
|
||||
* 78 bytes before it. The BCH poly id needed its own field because
|
||||
* rs_level now means the RS level (0..4), not the low byte of the
|
||||
* poly id.
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include "lzrs_lib.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "sha256.h"
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes.
|
||||
* Runs the lzply v4 entry_encode (lzip -> BCH), then RS-encodes
|
||||
* the result when rs_level > 0. blob_len_out is the compressed
|
||||
* stream length before BCH and RS, exactly as in v4, so a decoder
|
||||
* can reconstruct every layer length from the header alone:
|
||||
* BCH length from blob_size + poly id, RS length from the BCH
|
||||
* length + parity. Returns 0 on success. */
|
||||
int lzrs_entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
const ecc_opt_t *ecc, int rs_level,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32], uint16_t *crc16_out)
|
||||
{
|
||||
uint8_t *bch_stored = NULL, *rs_out = NULL;
|
||||
size_t bch_len = 0, blob_len = 0, rs_len = 0;
|
||||
int parity;
|
||||
if (rs_level < 0 || rs_level > 4)
|
||||
return -1;
|
||||
parity = rs_parity_for_level(rs_level);
|
||||
if (entry_encode(raw, raw_len, level, ecc,
|
||||
&bch_stored, &bch_len, &blob_len, poly_id_out,
|
||||
is_bch_out, level_out, sha_out, crc16_out) != 0)
|
||||
return -1;
|
||||
if (parity == 0) {
|
||||
*stored = bch_stored;
|
||||
*stored_len = bch_len;
|
||||
*blob_len_out = blob_len;
|
||||
return 0;
|
||||
}
|
||||
rs_len = rs_encoded_len(bch_len, parity);
|
||||
rs_out = xmalloc(rs_len ? rs_len : 1);
|
||||
if (rs_encode(bch_stored, bch_len, parity, rs_out) != rs_len) {
|
||||
free(bch_stored);
|
||||
free(rs_out);
|
||||
return -1;
|
||||
}
|
||||
free(bch_stored);
|
||||
*stored = rs_out;
|
||||
*stored_len = rs_len;
|
||||
*blob_len_out = blob_len;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* RS-decodes first (when rs_level > 0), then hands the result to
|
||||
* the v4 entry_decode (BCH two-pass + lzip + SHA-256). The BCH
|
||||
* length is reconstructed from blob_size + poly id, and the RS
|
||||
* length is checked against it, so a truncated or mis-sized
|
||||
* entry fails here instead of decoding garbage. Returns 0 on
|
||||
* success, -1 on any failure. */
|
||||
int lzrs_entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id, int rs_level,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint8_t **raw, size_t *raw_len,
|
||||
int *corrected_rs, int *corrected_bch,
|
||||
uint16_t want_crc16)
|
||||
{
|
||||
const bch_poly_t *poly = NULL;
|
||||
size_t bch_len;
|
||||
int parity, corr_rs = 0, corr_bch = 0, rc;
|
||||
*corrected_rs = 0;
|
||||
*corrected_bch = 0;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (rs_level < 0 || rs_level > 4)
|
||||
return -1;
|
||||
parity = rs_parity_for_level(rs_level);
|
||||
if (is_bch) {
|
||||
poly = bch_poly_by_id(poly_id);
|
||||
if (!poly)
|
||||
return -1;
|
||||
bch_len = bch_encoded_len(blob_size, poly);
|
||||
} else {
|
||||
bch_len = blob_size;
|
||||
}
|
||||
if (parity == 0) {
|
||||
if (stored_len != bch_len)
|
||||
return -1;
|
||||
rc = entry_decode(stored, stored_len, level,
|
||||
is_bch, poly_id, want_sha, blob_size,
|
||||
raw, raw_len, &corr_bch, want_crc16);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
*corrected_bch = corr_bch;
|
||||
return 0;
|
||||
}
|
||||
if (stored_len != rs_encoded_len(bch_len, parity))
|
||||
return -1;
|
||||
{
|
||||
uint8_t *bch_stored = xmalloc(bch_len ? bch_len : 1);
|
||||
if (rs_decode(stored, stored_len, bch_len, parity,
|
||||
bch_stored, &corr_rs) != 0) {
|
||||
free(bch_stored);
|
||||
return -1;
|
||||
}
|
||||
rc = entry_decode(bch_stored, bch_len, level,
|
||||
is_bch, poly_id, want_sha, blob_size,
|
||||
raw, raw_len, &corr_bch, want_crc16);
|
||||
free(bch_stored);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
*corrected_rs = corr_rs;
|
||||
*corrected_bch = corr_bch;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Entry header I/O. Layout (82 bytes, little-endian):
|
||||
* u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
* u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
* u32 mode, u64 mtime, u16 bch_poly_id, u16 crc16,
|
||||
* u32 header_crc32 (covers the 78 bytes before it).
|
||||
* crc16 is CRC-16/CCITT-FALSE of the blob (0xFFFF for a directory
|
||||
* entry, whose blob is empty). */
|
||||
|
||||
int lzrs_write_entry_header(FILE *f, const lzrs_ehdr_t *h)
|
||||
{
|
||||
uint8_t buf[LZRS_EHDR_SIZE];
|
||||
size_t plen = strlen(h->path);
|
||||
if (plen > 65535)
|
||||
return -1;
|
||||
memset(buf, 0, sizeof buf);
|
||||
put16le(buf + 0, (uint16_t)plen);
|
||||
buf[2] = h->level;
|
||||
buf[3] = h->rs_level;
|
||||
buf[4] = h->flags;
|
||||
buf[5] = h->reserved;
|
||||
put64le(buf + 6, h->orig_size);
|
||||
put64le(buf + 14, h->stored_size);
|
||||
put64le(buf + 22, h->blob_size);
|
||||
memcpy(buf + 30, h->sha, 32);
|
||||
put32le(buf + 62, h->mode);
|
||||
put64le(buf + 66, h->mtime);
|
||||
put16le(buf + 74, h->bch_poly_id);
|
||||
put16le(buf + 76, h->crc16);
|
||||
put32le(buf + 78, crc32_of(buf, 78));
|
||||
if (fwrite(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (plen > 0 && fwrite(h->path, 1, plen, f) != plen)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
int lzrs_read_entry_header(FILE *f, lzrs_ehdr_t *h)
|
||||
{
|
||||
uint8_t buf[LZRS_EHDR_SIZE];
|
||||
uint16_t plen;
|
||||
uint32_t want_crc, got_crc;
|
||||
memset(h, 0, sizeof *h);
|
||||
if (fread(buf, 1, 2, f) != 2)
|
||||
return -1;
|
||||
plen = get16le(buf);
|
||||
if (plen == 0)
|
||||
return 1;
|
||||
if (fread(buf + 2, 1, LZRS_EHDR_SIZE - 2, f) != LZRS_EHDR_SIZE - 2)
|
||||
return -1;
|
||||
want_crc = get32le(buf + 78);
|
||||
put32le(buf + 78, 0);
|
||||
got_crc = crc32_of(buf, 78);
|
||||
put32le(buf + 78, want_crc);
|
||||
if (got_crc != want_crc)
|
||||
return -1;
|
||||
h->level = buf[2];
|
||||
h->rs_level = buf[3];
|
||||
h->flags = buf[4];
|
||||
h->reserved = buf[5];
|
||||
h->orig_size = get64le(buf + 6);
|
||||
h->stored_size = get64le(buf + 14);
|
||||
h->blob_size = get64le(buf + 22);
|
||||
memcpy(h->sha, buf + 30, 32);
|
||||
h->mode = get32le(buf + 62);
|
||||
h->mtime = get64le(buf + 66);
|
||||
h->bch_poly_id = get16le(buf + 74);
|
||||
h->crc16 = get16le(buf + 76);
|
||||
if (h->level > 9)
|
||||
return -1;
|
||||
if (h->rs_level > 4)
|
||||
return -1;
|
||||
if (h->flags & FLAG_BCH) {
|
||||
if (!bch_poly_by_id(h->bch_poly_id))
|
||||
return -1;
|
||||
} else if (h->bch_poly_id != 0) {
|
||||
return -1;
|
||||
}
|
||||
/* crc16 is the blob CRC16 (see lzrs_lib.h). It is verified at
|
||||
* decode time by entry_decode / lzrs_entry_decode, not here:
|
||||
* header-only readers (-l / -i) must work without the data. */
|
||||
h->path = xmalloc((size_t)plen + 1);
|
||||
if (fread(h->path, 1, plen, f) != plen) {
|
||||
free(h->path);
|
||||
h->path = NULL;
|
||||
return -1;
|
||||
}
|
||||
h->path[plen] = 0;
|
||||
/* Reject paths that would escape the destination directory. */
|
||||
if (h->path[0] == 0x2f /* slash, written hex: a quoted char literal cannot pass through the ssh heredoc */ || strstr(h->path, "/../") != NULL ||
|
||||
strcmp(h->path, "..") == 0 ||
|
||||
(plen >= 3 && strcmp(h->path + plen - 3, "/..") == 0)) {
|
||||
free(h->path);
|
||||
h->path = NULL;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lzrs_read_global_header(FILE *f, uint32_t *count_out)
|
||||
{
|
||||
uint8_t buf[LZRS_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZRS_MAGIC, 4) != 0 || buf[4] != LZRS_VERSION)
|
||||
return -1;
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void lzrs_write_global_header(FILE *f, uint32_t count, int version)
|
||||
{
|
||||
uint8_t buf[LZRS_HDR_SIZE];
|
||||
memset(buf, 0, sizeof buf);
|
||||
memcpy(buf, LZRS_MAGIC, 4);
|
||||
buf[4] = (uint8_t)version;
|
||||
buf[5] = 0;
|
||||
put32le(buf + 6, count);
|
||||
fwrite(buf, 1, sizeof buf, f);
|
||||
}
|
||||
|
||||
int lzrs_read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out)
|
||||
{
|
||||
uint8_t buf[LZRS_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZRS_MAGIC, 4) != 0 || buf[4] != LZRS_VERSION)
|
||||
return -1;
|
||||
*version_out = buf[4];
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Scan an LZRS archive and record every entry. Same contract as
|
||||
* scan_archive: on success *end_off_out is the file offset of the
|
||||
* 2-byte end marker (which must be the last 2 bytes of the file).
|
||||
* Returns -1 (with a message) if the file is not a valid LZRS
|
||||
* archive, an entry header is corrupt, or there are trailing
|
||||
* bytes after the end marker. */
|
||||
int lzrs_scan_archive(const char *path, int *version_out,
|
||||
uint32_t *count_out, off_t *size_out,
|
||||
scan_list_t *entries, off_t *end_off_out)
|
||||
{
|
||||
struct stat st;
|
||||
FILE *f = fopen(path, "rb");
|
||||
off_t end_off;
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname, path,
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (fstat(fileno(f), &st) != 0) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (lzrs_read_global_header_full(f, version_out, count_out) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an lz_rs archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
memset(entries, 0, sizeof *entries);
|
||||
for (;;) {
|
||||
off_t off = ftello(f);
|
||||
lzrs_ehdr_t h;
|
||||
int r = lzrs_read_entry_header(f, &h);
|
||||
if (r == 1) { /* end marker */
|
||||
end_off = off;
|
||||
break;
|
||||
}
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: %s is truncated or has a corrupt entry header\n",
|
||||
lzply_progname, path);
|
||||
scan_list_free(entries);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (entries->len == entries->cap) {
|
||||
entries->cap = entries->cap ? entries->cap * 2 : 64;
|
||||
entries->v = xrealloc(entries->v,
|
||||
entries->cap * sizeof(scan_entry_t));
|
||||
}
|
||||
entries->v[entries->len].path = h.path; /* take ownership */
|
||||
entries->v[entries->len].offset = off;
|
||||
entries->v[entries->len].total_len =
|
||||
LZRS_EHDR_SIZE + (uint64_t)strlen(h.path) + h.stored_size;
|
||||
entries->v[entries->len].is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
entries->len++;
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: %s is truncated\n", lzply_progname, path);
|
||||
scan_list_free(entries);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (end_off != (off_t)st.st_size - 2 || ftello(f) != st.st_size) {
|
||||
fprintf(stderr, "%s: %s has trailing bytes after the end marker\n",
|
||||
lzply_progname, path);
|
||||
scan_list_free(entries);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
*size_out = st.st_size;
|
||||
*end_off_out = end_off;
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
/* lzrs_lib.h - LZRS v1 archive format and per-entry pipeline.
|
||||
*
|
||||
* lz_rs is lzply plus a Reed-Solomon layer. The pipeline per entry
|
||||
* is: raw bytes -> lzip compress (or store) -> BCH encode -> RS
|
||||
* encode. On decode the layers run in reverse: RS decode (fixes
|
||||
* whole-byte and burst errors), then BCH decode (fixes scattered
|
||||
* bit errors, two-pass, hash-gated), then lzip decompress, then a
|
||||
* SHA-256 check. No data is ever returned unless it hashes
|
||||
* correctly, exactly like lzply.
|
||||
*
|
||||
* LZRS v1 format (all integers little-endian). It is a NEW format:
|
||||
* the magic differs from lzply v4, so an old .lzply file is never
|
||||
* misread as LZRS (and lzply rejects .lzrs files). There is no
|
||||
* legacy support: v1 is the only LZRS version.
|
||||
* global header (16 bytes):
|
||||
* magic "LZRS", version u8 (=1), flags u8, entry_count u32,
|
||||
* reserved u64
|
||||
* entries, each:
|
||||
* u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
|
||||
* u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
|
||||
* u32 mode, u64 mtime, u16 bch_poly_id, u16 crc16, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 78 bytes before it; blob_size is the
|
||||
* length of the compressed stream before BCH and RS parity was
|
||||
* added; mtime is the source file modification time, seconds
|
||||
* since the epoch, UTC; the entry header is 82 bytes; crc16 is
|
||||
* CRC-16/CCITT-FALSE of the blob -- see below)
|
||||
* end marker: u16 path_len == 0
|
||||
* Level is the lzip level (1..9) of the blob, or 0 for a stored
|
||||
* (uncompressed) entry, exactly as in lzply v5. Flags: bit 1 =
|
||||
* directory, bit 2 = BCH mode (same bits as v5).
|
||||
* rs_level is the RS level (0..4): 0 = no RS parity, 1..4 = 8, 16,
|
||||
* 24, 32 parity symbols per 255-byte block (see rs.h). bch_poly_id
|
||||
* is the BCH polynomial id (0 when the entry has no BCH layer).
|
||||
* crc16 is CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no
|
||||
* reflection, xorout 0; check value crc16_of("123456789") == 0x29B1)
|
||||
* of the blob -- the compressed stream before BCH and RS parity
|
||||
* was added (for a stored entry the blob is the raw bytes; for a
|
||||
* directory entry the blob is empty, so crc16 == 0xFFFF). Writers
|
||||
* compute and store it; readers verify it after RS/BCH decoding
|
||||
* and before decompression. A mismatch is a clean failure, never a
|
||||
* misdecode; the SHA-256 check remains the final oracle. Archives
|
||||
* written before the CRC16 migration stored 0 here and are
|
||||
* rejected with a specific message (docs/lzrs-format.md).
|
||||
*/
|
||||
#ifndef LZRS_LIB_H
|
||||
#define LZRS_LIB_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "lzply_lib.h"
|
||||
#include "rs.h"
|
||||
|
||||
#define LZRS_MAGIC "LZRS"
|
||||
#define LZRS_VERSION 1 /* the only LZRS format version */
|
||||
#define LZRS_HDR_SIZE 16
|
||||
#define LZRS_EHDR_SIZE 82
|
||||
#define LZRS_END_MARKER 0
|
||||
|
||||
/* Entry header. rs_level is the RS level (0..4), not a BCH poly
|
||||
* id: the BCH poly id lives in bch_poly_id. crc16 is
|
||||
* CRC-16/CCITT-FALSE of the blob (see above). */
|
||||
typedef struct {
|
||||
char *path;
|
||||
uint8_t level, rs_level, flags, reserved;
|
||||
uint64_t orig_size, stored_size, blob_size;
|
||||
uint8_t sha[32];
|
||||
uint32_t mode;
|
||||
uint64_t mtime;
|
||||
uint16_t bch_poly_id;
|
||||
uint16_t crc16; /* CRC-16/CCITT-FALSE of the blob */
|
||||
} lzrs_ehdr_t;
|
||||
|
||||
int lzrs_write_entry_header(FILE *f, const lzrs_ehdr_t *h);
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
int lzrs_read_entry_header(FILE *f, lzrs_ehdr_t *h);
|
||||
int lzrs_read_global_header(FILE *f, uint32_t *count_out);
|
||||
void lzrs_write_global_header(FILE *f, uint32_t count, int version);
|
||||
/* Read the 16-byte global header, returning version and count.
|
||||
* Returns 0 on success, -1 if the file is not an LZRS archive. */
|
||||
int lzrs_read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out);
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes (lzip -> BCH -> RS).
|
||||
* Fills sha_out with SHA-256 of the raw bytes, and (when crc16_out
|
||||
* is non-NULL) *crc16_out with CRC-16/CCITT-FALSE of the blob.
|
||||
* *poly_id_out / *is_bch_out describe the BCH layer actually used,
|
||||
* for the entry header; *level_out is the level actually stored (0
|
||||
* when stored uncompressed). rs_level is the RS level (0..4).
|
||||
* Returns 0 on success. */
|
||||
int lzrs_entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
const ecc_opt_t *ecc, int rs_level,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32], uint16_t *crc16_out);
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes (RS -> BCH -> lzip).
|
||||
* Return values: 0 ok, -1 corrupt (RS uncorrectable, BCH
|
||||
* uncorrectable, CRC16 mismatch, lzip error, SHA-256 mismatch).
|
||||
* *corrected_rs receives the number of RS symbols corrected,
|
||||
* *corrected_bch the number of BCH bits corrected. `is_bch` /
|
||||
* `poly_id` / `rs_level` come from the entry header. `want_crc16`
|
||||
* is the CRC16 from the entry header: the decoded blob is
|
||||
* CRC-checked against it before decompression (see entry_decode). */
|
||||
int lzrs_entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id, int rs_level,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint8_t **raw, size_t *raw_len,
|
||||
int *corrected_rs, int *corrected_bch,
|
||||
uint16_t want_crc16);
|
||||
|
||||
/* Scan an LZRS archive and record every entry. Same contract as
|
||||
* scan_archive (see lzply_lib.h): returns 0 on success, -1 (with
|
||||
* a message) if the file is not a valid LZRS archive, an entry
|
||||
* header is corrupt, or there are trailing bytes after the end
|
||||
* marker. */
|
||||
int lzrs_scan_archive(const char *path, int *version_out,
|
||||
uint32_t *count_out, off_t *size_out,
|
||||
scan_list_t *entries, off_t *end_off_out);
|
||||
|
||||
#endif /* LZRS_LIB_H */
|
||||
@@ -1,436 +0,0 @@
|
||||
/* rs.c - Reed-Solomon codec: RS(255, 255-p) over GF(2^8), poly 0x11D.
|
||||
*
|
||||
* Byte order convention (shared by encoder and decoder): a codeword
|
||||
* is a sequence c[0..n-1] with c[0] the coefficient of x^(n-1),
|
||||
* i.e. the first byte is the highest-degree coefficient. Encoding
|
||||
* is systematic (data first, parity after) and the codeword is
|
||||
* divisible by g(x) = prod_{i=0}^{p-1} (x - alpha^i), so all p
|
||||
* syndromes S_i = r(alpha^i) are zero for a clean codeword.
|
||||
*
|
||||
* Decoding is the textbook pipeline: syndromes -> Berlekamp-Massey
|
||||
* (error-locator polynomial) -> Chien search (error positions) ->
|
||||
* Forney (error magnitudes) -> re-check the syndromes. Anything
|
||||
* that does not come back clean is a loud failure, never a silent
|
||||
* wrong answer at this layer (and the SHA-256 check above it is the
|
||||
* final oracle anyway).
|
||||
*/
|
||||
#include "rs.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* GF(2^8) tables, primitive polynomial 0x11D, primitive element 2. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static uint8_t rs_exp[512];
|
||||
static uint8_t rs_log[256];
|
||||
static int rs_tables_ready = 0;
|
||||
|
||||
static void rs_init_tables(void)
|
||||
{
|
||||
int i;
|
||||
int x = 1;
|
||||
if (rs_tables_ready)
|
||||
return;
|
||||
for (i = 0; i < 255; i++) {
|
||||
rs_exp[i] = (uint8_t)x;
|
||||
rs_log[x] = (uint8_t)i;
|
||||
x <<= 1;
|
||||
if (x & 0x100)
|
||||
x ^= 0x11D;
|
||||
}
|
||||
for (i = 255; i < 512; i++)
|
||||
rs_exp[i] = rs_exp[i - 255];
|
||||
rs_tables_ready = 1;
|
||||
}
|
||||
|
||||
static uint8_t gf_mul(uint8_t a, uint8_t b)
|
||||
{
|
||||
if (a == 0 || b == 0)
|
||||
return 0;
|
||||
return rs_exp[rs_log[a] + rs_log[b]];
|
||||
}
|
||||
|
||||
static uint8_t gf_div(uint8_t a, uint8_t b)
|
||||
{
|
||||
if (a == 0)
|
||||
return 0;
|
||||
/* b != 0 always at call sites; guard anyway. */
|
||||
if (b == 0)
|
||||
return 0;
|
||||
return rs_exp[rs_log[a] - rs_log[b] + 255];
|
||||
}
|
||||
|
||||
|
||||
/* Evaluate a polynomial given in decreasing-degree order (coef[0] is
|
||||
* the highest-degree coefficient) at x, by Horner. */
|
||||
static uint8_t poly_eval_dec(const uint8_t *coef, size_t n, uint8_t x)
|
||||
{
|
||||
uint8_t r = 0;
|
||||
size_t i;
|
||||
for (i = 0; i < n; i++)
|
||||
r = (uint8_t)(gf_mul(r, x) ^ coef[i]);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Evaluate a polynomial given in increasing-degree order (coef[0] is
|
||||
* the constant term) at x. */
|
||||
static uint8_t poly_eval_inc(const uint8_t *coef, size_t n, uint8_t x)
|
||||
{
|
||||
uint8_t r = 0;
|
||||
size_t i = n;
|
||||
while (i-- > 0)
|
||||
r = (uint8_t)(gf_mul(r, x) ^ coef[i]);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Parameters */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
int rs_parity_for_level(int level)
|
||||
{
|
||||
switch (level) {
|
||||
case 0: return 0;
|
||||
case 1: return 8;
|
||||
case 2: return 16;
|
||||
case 3: return 24;
|
||||
case 4: return 32;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
int rs_data_per_block(int parity)
|
||||
{
|
||||
if (parity < 0 || parity > RS_MAX_PARITY || (parity & 1))
|
||||
return -1;
|
||||
return RS_N - parity;
|
||||
}
|
||||
|
||||
size_t rs_encoded_len(size_t len, int parity)
|
||||
{
|
||||
int k;
|
||||
size_t nblocks, last;
|
||||
if (parity == 0)
|
||||
return len;
|
||||
k = rs_data_per_block(parity);
|
||||
if (k <= 0 || len == 0)
|
||||
return 0;
|
||||
nblocks = (len + (size_t)k - 1) / (size_t)k;
|
||||
last = len - (nblocks - 1) * (size_t)k; /* 1..k */
|
||||
return (nblocks - 1) * (size_t)RS_N + last + (size_t)parity;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Generator polynomial g(x) = prod_{i=0}^{p-1} (x + alpha^i), */
|
||||
/* returned in increasing-degree order: gen[0] is the constant term, */
|
||||
/* gen[p] == 1. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void rs_generator(int parity, uint8_t *gen)
|
||||
{
|
||||
int i, j, deg = 0;
|
||||
memset(gen, 0, (size_t)(parity + 1));
|
||||
gen[0] = 1;
|
||||
for (i = 0; i < parity; i++) {
|
||||
uint8_t root = rs_exp[i]; /* alpha^i, fcr = 0 */
|
||||
/* Multiply the current g (degree deg) by (x + root). */
|
||||
uint8_t ng[RS_MAX_PARITY + 1];
|
||||
memset(ng, 0, sizeof ng);
|
||||
for (j = 0; j <= deg; j++) {
|
||||
ng[j] ^= gf_mul(gen[j], root); /* root * g[j] * x^j */
|
||||
ng[j + 1] ^= gen[j]; /* g[j] * x^(j+1) */
|
||||
}
|
||||
deg++;
|
||||
memcpy(gen, ng, (size_t)(deg + 1));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Encode */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
int rs_encode_block(const uint8_t *data, size_t data_len,
|
||||
int parity, uint8_t *out)
|
||||
{
|
||||
uint8_t gen[RS_MAX_PARITY + 1];
|
||||
uint8_t w[RS_N];
|
||||
int k, i, j;
|
||||
if (parity < 0 || parity > RS_MAX_PARITY || (parity & 1))
|
||||
return -1;
|
||||
if (parity == 0) {
|
||||
memcpy(out, data, data_len);
|
||||
return 0;
|
||||
}
|
||||
k = RS_N - parity;
|
||||
if (data_len > (size_t)k)
|
||||
return -1;
|
||||
rs_init_tables();
|
||||
rs_generator(parity, gen);
|
||||
/* w = data (zero-padded to k) followed by parity zeros: the
|
||||
* coefficients of m(x) = data(x) * x^parity in decreasing order.
|
||||
* Long-divide by g(x); the remainder is the parity. */
|
||||
memset(w, 0, sizeof w);
|
||||
memcpy(w, data, data_len);
|
||||
for (i = 0; i < k; i++) {
|
||||
uint8_t coef = w[i];
|
||||
if (coef == 0)
|
||||
continue;
|
||||
for (j = 1; j <= parity; j++)
|
||||
w[i + j] ^= gf_mul(gen[parity - j], coef);
|
||||
}
|
||||
memcpy(out, data, data_len);
|
||||
memcpy(out + data_len, w + k, (size_t)parity);
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t rs_encode(const uint8_t *data, size_t len, int parity,
|
||||
uint8_t *out)
|
||||
{
|
||||
int k;
|
||||
size_t off = 0, ooff = 0;
|
||||
if (parity == 0) {
|
||||
memcpy(out, data, len);
|
||||
return len;
|
||||
}
|
||||
k = rs_data_per_block(parity);
|
||||
while (off < len) {
|
||||
size_t chunk = len - off;
|
||||
if (chunk > (size_t)k)
|
||||
chunk = (size_t)k;
|
||||
rs_encode_block(data + off, chunk, parity, out + ooff);
|
||||
off += chunk;
|
||||
ooff += chunk + (size_t)parity;
|
||||
}
|
||||
return ooff;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Decode */
|
||||
/* */
|
||||
/* Syndromes S_i = r(alpha^i), i = 0..p-1, fcr = 0. An error at byte */
|
||||
/* j (0 = first byte) with value e contributes e * (alpha^(n-1-j))^i */
|
||||
/* to S_i, so with X_j = alpha^(n-1-j) the syndromes are the power */
|
||||
/* sums S_i = sum_j e_j * X_j^i. Berlekamp-Massey on S_0..S_{p-1} */
|
||||
/* gives the error-locator Lambda(x) = prod_j (1 - X_j x); Chien */
|
||||
/* search finds the roots (x = X_j^-1), and Forney gives the */
|
||||
/* magnitudes e_j = X_j * Omega(X_j^-1) / Lambda-deriv(X_j^-1), */
|
||||
/* where Omega(x) = (S(x) * Lambda(x)) mod x^p. All arithmetic is */
|
||||
/* in GF(2^8), so subtraction is addition. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* Syndromes of a full n-byte received word (decreasing-degree
|
||||
* order). Returns 1 if all zero (no errors), else 0. */
|
||||
static int rs_syndromes(const uint8_t *r, int n, int parity,
|
||||
uint8_t *syn)
|
||||
{
|
||||
int i, allzero = 1;
|
||||
for (i = 0; i < parity; i++) {
|
||||
syn[i] = poly_eval_dec(r, (size_t)n, rs_exp[i]);
|
||||
if (syn[i] != 0)
|
||||
allzero = 0;
|
||||
}
|
||||
return allzero;
|
||||
}
|
||||
|
||||
/* Berlekamp-Massey: minimal connection polynomial Lambda for the
|
||||
* syndrome sequence syn[0..parity-1]. Lambda is returned in
|
||||
* increasing-degree order (lam[0] == 1); *deg_out is its degree
|
||||
* (= number of errors, when decoding succeeds). */
|
||||
static void rs_berlekamp_massey(const uint8_t *syn, int parity,
|
||||
uint8_t *lam, int *deg_out)
|
||||
{
|
||||
uint8_t c[RS_MAX_PARITY + 1];
|
||||
uint8_t b[RS_MAX_PARITY + 1];
|
||||
uint8_t t[RS_MAX_PARITY + 1];
|
||||
int l = 0, m = 1, n, i;
|
||||
uint8_t bb = 1;
|
||||
memset(c, 0, sizeof c);
|
||||
memset(b, 0, sizeof b);
|
||||
c[0] = 1;
|
||||
b[0] = 1;
|
||||
for (n = 0; n < parity; n++) {
|
||||
uint8_t d = syn[n];
|
||||
for (i = 1; i <= l; i++)
|
||||
d ^= gf_mul(c[i], syn[n - i]);
|
||||
if (d == 0) {
|
||||
m++;
|
||||
continue;
|
||||
}
|
||||
memcpy(t, c, sizeof t);
|
||||
{
|
||||
uint8_t coef = gf_div(d, bb);
|
||||
for (i = 0; i + m <= parity; i++) {
|
||||
if (b[i] == 0)
|
||||
continue;
|
||||
c[i + m] ^= gf_mul(coef, b[i]);
|
||||
}
|
||||
}
|
||||
if (2 * l <= n) {
|
||||
l = n + 1 - l;
|
||||
memcpy(b, t, sizeof b);
|
||||
bb = d;
|
||||
m = 1;
|
||||
} else {
|
||||
m++;
|
||||
}
|
||||
}
|
||||
memcpy(lam, c, (size_t)(parity + 1));
|
||||
*deg_out = l;
|
||||
}
|
||||
|
||||
/* Formal derivative of lam (increasing order) in characteristic 2:
|
||||
* only odd-degree terms survive: deriv(x) = sum over odd i of
|
||||
* lam[i] x^(i-1). Returned in increasing order. */
|
||||
static void rs_lambda_deriv(const uint8_t *lam, int deg, uint8_t *der)
|
||||
{
|
||||
int i;
|
||||
memset(der, 0, (size_t)(deg + 1));
|
||||
for (i = 1; i <= deg; i += 2)
|
||||
der[i - 1] = lam[i];
|
||||
}
|
||||
|
||||
/* Omega(x) = (S(x) * Lambda(x)) mod x^parity, increasing order.
|
||||
* S(x) = sum syn[i] x^i. */
|
||||
static void rs_omega(const uint8_t *syn, const uint8_t *lam, int parity,
|
||||
uint8_t *om)
|
||||
{
|
||||
int i, j;
|
||||
memset(om, 0, (size_t)parity);
|
||||
for (i = 0; i < parity; i++) {
|
||||
if (syn[i] == 0)
|
||||
continue;
|
||||
for (j = 0; j <= parity - 1 - i; j++) {
|
||||
if (lam[j] == 0)
|
||||
continue;
|
||||
om[i + j] ^= gf_mul(syn[i], lam[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Decode one full n-byte received word in place (corrects it).
|
||||
* Returns the number of symbols corrected, or -1 if uncorrectable.
|
||||
* n is 255 for a full block; shortened blocks are reconstructed to
|
||||
* the full 255 bytes by the caller (zero pad) before calling this.
|
||||
* pad_from and pad_to delimit the zero-pad byte range [pad_from,
|
||||
* pad_to) in the word, or -1 and -1 for a full block: after
|
||||
* correction the pad must still be zero, else this is a
|
||||
* miscorrection. */
|
||||
static int rs_decode_full(uint8_t *word, int n, int parity,
|
||||
int pad_from, int pad_to)
|
||||
{
|
||||
uint8_t syn[RS_MAX_PARITY];
|
||||
uint8_t lam[RS_MAX_PARITY + 1];
|
||||
uint8_t om[RS_MAX_PARITY];
|
||||
uint8_t der[RS_MAX_PARITY + 1];
|
||||
int deg, i, j, nerr = 0, corrected = 0;
|
||||
if (parity == 0)
|
||||
return 0;
|
||||
rs_init_tables();
|
||||
if (rs_syndromes(word, n, parity, syn))
|
||||
return 0;
|
||||
rs_berlekamp_massey(syn, parity, lam, °);
|
||||
if (deg == 0 || deg > parity / 2)
|
||||
return -1;
|
||||
rs_omega(syn, lam, parity, om);
|
||||
rs_lambda_deriv(lam, deg, der);
|
||||
/* Chien search: byte j has X_j = alpha^(n-1-j); Lambda has a
|
||||
* root at x = X_j^-1 = alpha^(j-n+1). */
|
||||
for (j = 0; j < n; j++) {
|
||||
int idx = (j - n + 1) % 255;
|
||||
uint8_t xinv;
|
||||
uint8_t num, den, mag;
|
||||
if (idx < 0)
|
||||
idx += 255;
|
||||
xinv = rs_exp[idx];
|
||||
if (poly_eval_inc(lam, (size_t)deg + 1, xinv) != 0)
|
||||
continue;
|
||||
nerr++;
|
||||
/* Forney: e_j = X_j * Omega(X_j^-1) / Lambda-deriv(X_j^-1). */
|
||||
num = poly_eval_inc(om, (size_t)parity, xinv);
|
||||
den = poly_eval_inc(der, (size_t)deg, xinv);
|
||||
if (den == 0)
|
||||
return -1;
|
||||
mag = gf_mul(rs_exp[(n - 1 - j) % 255], gf_div(num, den));
|
||||
if (mag == 0)
|
||||
return -1;
|
||||
word[j] ^= mag;
|
||||
corrected++;
|
||||
}
|
||||
if (nerr != deg)
|
||||
return -1;
|
||||
if (pad_from >= 0) {
|
||||
for (i = pad_from; i < pad_to; i++)
|
||||
if (word[i] != 0)
|
||||
return -1;
|
||||
}
|
||||
if (!rs_syndromes(word, n, parity, syn))
|
||||
return -1;
|
||||
return corrected;
|
||||
}
|
||||
|
||||
int rs_decode_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
int parity, uint8_t *out, int *corrected)
|
||||
{
|
||||
uint8_t word[RS_N];
|
||||
int k, corr;
|
||||
if (parity < 0 || parity > RS_MAX_PARITY || (parity & 1))
|
||||
return -1;
|
||||
if (in_len != data_len + (size_t)parity)
|
||||
return -1;
|
||||
if (parity == 0) {
|
||||
memcpy(out, in, data_len);
|
||||
if (corrected)
|
||||
*corrected = 0;
|
||||
return 0;
|
||||
}
|
||||
k = RS_N - parity;
|
||||
if (data_len > (size_t)k)
|
||||
return -1;
|
||||
rs_init_tables();
|
||||
memset(word, 0, sizeof word);
|
||||
memcpy(word, in, data_len);
|
||||
memcpy(word + k, in + data_len, (size_t)parity);
|
||||
corr = rs_decode_full(word, RS_N, parity,
|
||||
(int)data_len, k);
|
||||
if (corr < 0)
|
||||
return -1;
|
||||
memcpy(out, word, data_len);
|
||||
if (corrected)
|
||||
*corrected = corr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int rs_decode(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
int parity, uint8_t *out, int *corrected)
|
||||
{
|
||||
int k, total_corr = 0;
|
||||
size_t off = 0, ooff = 0, ioff = 0;
|
||||
if (parity < 0 || parity > RS_MAX_PARITY || (parity & 1))
|
||||
return -1;
|
||||
if (in_len != rs_encoded_len(data_len, parity))
|
||||
return -1;
|
||||
if (parity == 0) {
|
||||
memcpy(out, in, data_len);
|
||||
if (corrected)
|
||||
*corrected = 0;
|
||||
return 0;
|
||||
}
|
||||
k = RS_N - parity;
|
||||
while (off < data_len) {
|
||||
size_t chunk = data_len - off;
|
||||
int corr = 0;
|
||||
if (chunk > (size_t)k)
|
||||
chunk = (size_t)k;
|
||||
if (rs_decode_block(in + ioff, chunk + (size_t)parity, chunk,
|
||||
parity, out + ooff, &corr) != 0)
|
||||
return -1;
|
||||
total_corr += corr;
|
||||
off += chunk;
|
||||
ooff += chunk;
|
||||
ioff += chunk + (size_t)parity;
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = total_corr;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/* rs.h - Reed-Solomon error correction for lz_rs (LZRS v1).
|
||||
*
|
||||
* RS(255, 255-p) over GF(2^8), primitive polynomial 0x11D, primitive
|
||||
* element alpha = 2, first consecutive root fcr = 0, i.e. the
|
||||
* generator is g(x) = prod_{i=0}^{p-1} (x - alpha^i). Systematic
|
||||
* encoding: codeword = data || parity, first byte = highest-degree
|
||||
* coefficient. A block corrects up to p/2 symbol (byte) errors.
|
||||
*
|
||||
* Blocks are shortened: the last block of a buffer holds fewer than
|
||||
* k = 255-p data bytes; it is encoded as if zero-padded to k bytes,
|
||||
* but only the data bytes present plus the p parity bytes are stored.
|
||||
* The decoder reconstructs the zero pad (those symbols were never
|
||||
* stored, so they cannot be corrupt) and, after correction, checks
|
||||
* the pad is still zero -- a miscorrection that flips a pad symbol
|
||||
* is rejected outright.
|
||||
*
|
||||
* The codec is self-contained: encoder and decoder share the same
|
||||
* generator, so no external RS implementation is needed. A wrong
|
||||
* decode that slips past the syndrome check is still caught by the
|
||||
* SHA-256 check in lzrs_entry_decode -- no data is ever returned
|
||||
* unless it hashes correctly, exactly like the BCH two-pass rule.
|
||||
*/
|
||||
#ifndef LZRS_RS_H
|
||||
#define LZRS_RS_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define RS_N 255 /* codeword length (symbols) */
|
||||
#define RS_MAX_PARITY 32 /* level 4 */
|
||||
|
||||
/* -r level -> parity symbols per 255-byte block. 0 -> 0 (no RS),
|
||||
* 1 -> 8, 2 -> 16, 3 -> 24, 4 -> 32. Returns -1 for an invalid
|
||||
* level. Correctable symbol errors per block = parity/2. */
|
||||
int rs_parity_for_level(int level);
|
||||
|
||||
/* Data symbols per block for this parity: 255 - parity. */
|
||||
int rs_data_per_block(int parity);
|
||||
|
||||
/* Total stored bytes for a buffer of len data bytes (all blocks).
|
||||
* 0 when len == 0. */
|
||||
size_t rs_encoded_len(size_t len, int parity);
|
||||
|
||||
/* Encode one block: data_len <= rs_data_per_block(parity). out must
|
||||
* hold data_len + parity bytes (data, then parity). Returns 0 on
|
||||
* success, -1 on a bad parity or an oversize block. */
|
||||
int rs_encode_block(const uint8_t *data, size_t data_len,
|
||||
int parity, uint8_t *out);
|
||||
|
||||
/* Decode one block: in_len must equal data_len + parity. out must
|
||||
* hold data_len bytes. Returns 0 on success, -1 if uncorrectable
|
||||
* (or if the zero pad of a shortened block came back nonzero, i.e.
|
||||
* a miscorrection). *corrected (if non-NULL) = number of symbols
|
||||
* corrected. */
|
||||
int rs_decode_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
int parity, uint8_t *out, int *corrected);
|
||||
|
||||
/* Encode a whole buffer (splits into blocks of rs_data_per_block).
|
||||
* out must hold rs_encoded_len(len, parity) bytes. Returns the
|
||||
* stored length. */
|
||||
size_t rs_encode(const uint8_t *data, size_t len, int parity,
|
||||
uint8_t *out);
|
||||
|
||||
/* Decode a whole buffer: data_len is the original data length.
|
||||
* Returns 0 on success, -1 if any block is uncorrectable or the
|
||||
* lengths do not match. *corrected (if non-NULL) = total symbols
|
||||
* corrected across blocks. */
|
||||
int rs_decode(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
int parity, uint8_t *out, int *corrected);
|
||||
|
||||
#endif /* LZRS_RS_H */
|
||||
@@ -1,387 +0,0 @@
|
||||
/* rs_test.c - unit tests for the Reed-Solomon codec (rs.c).
|
||||
*
|
||||
* Covers: level -> parity mapping, encoded lengths, clean
|
||||
* round-trips at every parity for many buffer lengths (including
|
||||
* shortened last blocks and empty input), determinism, an
|
||||
* independent re-implementation cross-check of the encoder (own
|
||||
* GF tables, own generator build, own polynomial division), a
|
||||
* syndrome-zero check on every encoded block, and corruption
|
||||
* recovery: random symbol errors and burst errors up to t = p/2
|
||||
* per block must decode back to the exact original, while t+1
|
||||
* errors in one block must never decode back to the original
|
||||
* (it must fail loudly, or -- far worse -- miscorrect, which
|
||||
* this test treats as a failure).
|
||||
*
|
||||
* Deterministic: fixed PRNG seeds, no wall-clock or random device.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "rs.h"
|
||||
|
||||
static int fails = 0;
|
||||
static int checks = 0;
|
||||
|
||||
#define CHECK(cond, ...) do { \
|
||||
checks++; \
|
||||
if (!(cond)) { \
|
||||
fails++; \
|
||||
printf("FAIL: "); \
|
||||
printf(__VA_ARGS__); \
|
||||
printf("\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* xorshift32, deterministic. */
|
||||
static uint32_t rng_state = 0x12345678u;
|
||||
static uint32_t rnd32(void)
|
||||
{
|
||||
rng_state ^= rng_state << 13;
|
||||
rng_state ^= rng_state >> 17;
|
||||
rng_state ^= rng_state << 5;
|
||||
return rng_state;
|
||||
}
|
||||
|
||||
static void rnd_bytes(uint8_t *p, size_t n)
|
||||
{
|
||||
size_t i;
|
||||
for (i = 0; i < n; i++)
|
||||
p[i] = (uint8_t)(rnd32() & 0xff);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Independent GF(2^8) tables and encoder, written separately from */
|
||||
/* rs.c so the cross-check is meaningful. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static uint8_t t_exp[512];
|
||||
static uint8_t t_log[256];
|
||||
|
||||
static void t_init(void)
|
||||
{
|
||||
int i, x = 1;
|
||||
for (i = 0; i < 255; i++) {
|
||||
t_exp[i] = (uint8_t)x;
|
||||
t_log[x] = (uint8_t)i;
|
||||
x <<= 1;
|
||||
if (x & 0x100)
|
||||
x ^= 0x11D;
|
||||
}
|
||||
for (i = 255; i < 512; i++)
|
||||
t_exp[i] = t_exp[i - 255];
|
||||
}
|
||||
|
||||
static uint8_t t_mul(uint8_t a, uint8_t b)
|
||||
{
|
||||
if (a == 0 || b == 0)
|
||||
return 0;
|
||||
return t_exp[t_log[a] + t_log[b]];
|
||||
}
|
||||
|
||||
/* Generator coefficients in increasing-degree order, built by
|
||||
* multiplying out prod (x + alpha^i). */
|
||||
static void t_generator(int parity, uint8_t *gen)
|
||||
{
|
||||
int i, j, deg = 0;
|
||||
memset(gen, 0, (size_t)(parity + 1));
|
||||
gen[0] = 1;
|
||||
for (i = 0; i < parity; i++) {
|
||||
uint8_t ng[33];
|
||||
uint8_t root = t_exp[i];
|
||||
memset(ng, 0, sizeof ng);
|
||||
for (j = 0; j <= deg; j++) {
|
||||
ng[j] ^= t_mul(gen[j], root);
|
||||
ng[j + 1] ^= gen[j];
|
||||
}
|
||||
deg++;
|
||||
memcpy(gen, ng, (size_t)(deg + 1));
|
||||
}
|
||||
}
|
||||
|
||||
/* Independent systematic encode of one block: remainder of
|
||||
* data(x) * x^parity divided by g(x), computed by explicit
|
||||
* coefficient elimination on the full-length array. */
|
||||
static void t_encode_block(const uint8_t *data, size_t data_len,
|
||||
int parity, uint8_t *out)
|
||||
{
|
||||
uint8_t gen[33];
|
||||
uint8_t w[255];
|
||||
int k = 255 - parity;
|
||||
int i, j;
|
||||
t_generator(parity, gen);
|
||||
memset(w, 0, sizeof w);
|
||||
memcpy(w, data, data_len);
|
||||
for (i = 0; i < k; i++) {
|
||||
uint8_t coef = w[i];
|
||||
if (coef == 0)
|
||||
continue;
|
||||
for (j = 0; j <= parity; j++)
|
||||
w[i + j] ^= t_mul(gen[parity - j], coef);
|
||||
}
|
||||
memcpy(out, data, data_len);
|
||||
memcpy(out + data_len, w + k, (size_t)parity);
|
||||
}
|
||||
|
||||
/* Syndromes of a codeword (first byte = highest degree): all must
|
||||
* be zero for a valid codeword. Returns 1 when clean. */
|
||||
static int t_syndromes_zero(const uint8_t *cw, int n, int parity)
|
||||
{
|
||||
int i, j;
|
||||
for (i = 0; i < parity; i++) {
|
||||
uint8_t x = t_exp[i];
|
||||
uint8_t r = 0;
|
||||
for (j = 0; j < n; j++)
|
||||
r = (uint8_t)(t_mul(r, x) ^ cw[j]);
|
||||
if (r != 0)
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void test_levels(void)
|
||||
{
|
||||
CHECK(rs_parity_for_level(0) == 0, "level 0 parity");
|
||||
CHECK(rs_parity_for_level(1) == 8, "level 1 parity");
|
||||
CHECK(rs_parity_for_level(2) == 16, "level 2 parity");
|
||||
CHECK(rs_parity_for_level(3) == 24, "level 3 parity");
|
||||
CHECK(rs_parity_for_level(4) == 32, "level 4 parity");
|
||||
CHECK(rs_parity_for_level(5) == -1, "level 5 rejected");
|
||||
CHECK(rs_parity_for_level(-1) == -1, "level -1 rejected");
|
||||
CHECK(rs_data_per_block(32) == 223, "k for p=32");
|
||||
CHECK(rs_data_per_block(8) == 247, "k for p=8");
|
||||
CHECK(rs_data_per_block(0) == 255, "k for p=0");
|
||||
CHECK(rs_encoded_len(0, 32) == 0, "empty encodes to 0");
|
||||
CHECK(rs_encoded_len(223, 32) == 255, "223 bytes -> one full block");
|
||||
CHECK(rs_encoded_len(224, 32) == 255 + 1 + 32, "224 bytes -> full + short");
|
||||
CHECK(rs_encoded_len(446, 32) == 510, "446 bytes -> two full blocks");
|
||||
CHECK(rs_encoded_len(100, 0) == 100, "parity 0 is passthrough");
|
||||
}
|
||||
|
||||
static void test_roundtrips(void)
|
||||
{
|
||||
static const size_t lens[] = { 0, 1, 2, 100, 222, 223, 224, 225,
|
||||
255, 446, 447, 500, 1000, 4096, 65536 };
|
||||
static const int parities[] = { 0, 8, 16, 24, 32 };
|
||||
size_t li, pi;
|
||||
for (pi = 0; pi < sizeof parities / sizeof parities[0]; pi++) {
|
||||
int p = parities[pi];
|
||||
for (li = 0; li < sizeof lens / sizeof lens[0]; li++) {
|
||||
size_t len = lens[li];
|
||||
size_t elen = rs_encoded_len(len, p);
|
||||
uint8_t *data = malloc(len ? len : 1);
|
||||
uint8_t *enc = malloc(elen ? elen : 1);
|
||||
uint8_t *enc2 = malloc(elen ? elen : 1);
|
||||
uint8_t *dec = malloc(len ? len : 1);
|
||||
int corr = -1, rc;
|
||||
rnd_bytes(data, len);
|
||||
rc = (int)rs_encode(data, len, p, enc);
|
||||
CHECK(rc == (int)elen, "encode length len=%zu p=%d", len, p);
|
||||
rc = (int)rs_encode(data, len, p, enc2);
|
||||
CHECK(rc == (int)elen && memcmp(enc, enc2, elen) == 0,
|
||||
"determinism len=%zu p=%d", len, p);
|
||||
rc = rs_decode(enc, elen, len, p, dec, &corr);
|
||||
CHECK(rc == 0 && corr == 0 && memcmp(data, dec, len) == 0,
|
||||
"clean roundtrip len=%zu p=%d", len, p);
|
||||
free(data);
|
||||
free(enc);
|
||||
free(enc2);
|
||||
free(dec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void test_encoder_crosscheck(void)
|
||||
{
|
||||
static const int parities[] = { 8, 16, 24, 32 };
|
||||
size_t pi, trial;
|
||||
t_init();
|
||||
for (pi = 0; pi < sizeof parities / sizeof parities[0]; pi++) {
|
||||
int p = parities[pi];
|
||||
int k = 255 - p;
|
||||
for (trial = 0; trial < 200; trial++) {
|
||||
/* Random block length: full blocks and shortened ones. */
|
||||
size_t dlen = 1 + (rnd32() % (uint32_t)k);
|
||||
uint8_t *data = malloc(dlen);
|
||||
uint8_t *mine = malloc(dlen + (size_t)p);
|
||||
uint8_t *ref = malloc(dlen + (size_t)p);
|
||||
uint8_t full[255];
|
||||
int rc;
|
||||
rnd_bytes(data, dlen);
|
||||
rc = rs_encode_block(data, dlen, p, mine);
|
||||
CHECK(rc == 0, "encode_block rc p=%d dlen=%zu", p, dlen);
|
||||
t_encode_block(data, dlen, p, ref);
|
||||
CHECK(memcmp(mine, ref, dlen + (size_t)p) == 0,
|
||||
"encoder matches independent impl p=%d dlen=%zu", p, dlen);
|
||||
/* Syndrome-zero on the reconstructed full word. */
|
||||
memset(full, 0, sizeof full);
|
||||
memcpy(full, mine, dlen);
|
||||
memcpy(full + k, mine + dlen, (size_t)p);
|
||||
CHECK(t_syndromes_zero(full, 255, p),
|
||||
"syndromes zero p=%d dlen=%zu", p, dlen);
|
||||
free(data);
|
||||
free(mine);
|
||||
free(ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Corrupt exactly nerr distinct symbols of buf (length n) at
|
||||
* pseudo-random positions, each XORed with a random nonzero byte.
|
||||
* Positions are returned in pos_out when non-NULL. */
|
||||
static void corrupt_symbols(uint8_t *buf, size_t n, int nerr,
|
||||
long *pos_out)
|
||||
{
|
||||
long picked[64];
|
||||
int i;
|
||||
for (i = 0; i < nerr; i++) {
|
||||
long pos;
|
||||
int dup, q;
|
||||
do {
|
||||
pos = (long)(rnd32() % (uint32_t)n);
|
||||
dup = 0;
|
||||
for (q = 0; q < i; q++)
|
||||
if (picked[q] == pos)
|
||||
dup = 1;
|
||||
} while (dup);
|
||||
picked[i] = pos;
|
||||
if (pos_out)
|
||||
pos_out[i] = pos;
|
||||
buf[pos] ^= (uint8_t)(1 + (rnd32() % 255));
|
||||
}
|
||||
}
|
||||
|
||||
/* One corruption trial: encode data, corrupt the encoded buffer,
|
||||
* decode, and check the outcome. When recover is set, the decode
|
||||
* must succeed and return the exact original; otherwise it must
|
||||
* not return the original (rc != 0, or rc == 0 with wrong data,
|
||||
* which counts as a miscorrection and fails the test). */
|
||||
static void corruption_trial(const uint8_t *data, size_t len, int p,
|
||||
int nerr, int recover, int burst)
|
||||
{
|
||||
size_t elen = rs_encoded_len(len, p);
|
||||
uint8_t *enc = malloc(elen ? elen : 1);
|
||||
uint8_t *dec = malloc(len ? len : 1);
|
||||
int corr = -1, rc, i;
|
||||
rs_encode(data, len, p, enc);
|
||||
if (burst) {
|
||||
/* One contiguous run of nerr bytes inside a single block:
|
||||
* start it at a random offset within the first block. */
|
||||
size_t start = (size_t)(rnd32() % 200);
|
||||
if (start + (size_t)nerr > elen)
|
||||
start = 0;
|
||||
for (i = 0; i < nerr; i++)
|
||||
enc[start + (size_t)i] ^= (uint8_t)(1 + (rnd32() % 255));
|
||||
} else {
|
||||
corrupt_symbols(enc, elen, nerr, NULL);
|
||||
}
|
||||
rc = rs_decode(enc, elen, len, p, dec, &corr);
|
||||
if (recover) {
|
||||
CHECK(rc == 0, "recover rc len=%zu p=%d nerr=%d burst=%d",
|
||||
len, p, nerr, burst);
|
||||
if (rc == 0) {
|
||||
CHECK(corr == nerr, "corrected count len=%zu p=%d nerr=%d",
|
||||
len, p, nerr);
|
||||
CHECK(memcmp(data, dec, len) == 0,
|
||||
"recover data len=%zu p=%d nerr=%d burst=%d",
|
||||
len, p, nerr, burst);
|
||||
}
|
||||
} else {
|
||||
if (rc == 0 && memcmp(data, dec, len) == 0) {
|
||||
/* t+1 errors decoded back to the original: only
|
||||
* possible if the corruption cancelled itself out,
|
||||
* which cannot happen (every corrupted byte changed).
|
||||
* Treat as a hard failure. */
|
||||
CHECK(0, "t+1 errors decoded to original len=%zu p=%d nerr=%d",
|
||||
len, p, nerr);
|
||||
} else if (rc == 0) {
|
||||
CHECK(0, "MIS_CORRECTION len=%zu p=%d nerr=%d burst=%d",
|
||||
len, p, nerr, burst);
|
||||
}
|
||||
}
|
||||
free(enc);
|
||||
free(dec);
|
||||
}
|
||||
|
||||
static void test_corruption(void)
|
||||
{
|
||||
static const int parities[] = { 8, 16, 24, 32 };
|
||||
static const size_t lens[] = { 223, 224, 500, 1000, 5000 };
|
||||
size_t pi, li;
|
||||
int e, trial;
|
||||
for (pi = 0; pi < sizeof parities / sizeof parities[0]; pi++) {
|
||||
int p = parities[pi];
|
||||
int t = p / 2;
|
||||
for (li = 0; li < sizeof lens / sizeof lens[0]; li++) {
|
||||
size_t len = lens[li];
|
||||
uint8_t *data = malloc(len);
|
||||
rnd_bytes(data, len);
|
||||
/* Every error count up to t must recover, scattered
|
||||
* and burst, several trials each. */
|
||||
for (e = 1; e <= t; e++) {
|
||||
for (trial = 0; trial < 3; trial++)
|
||||
corruption_trial(data, len, p, e, 1, 0);
|
||||
for (trial = 0; trial < 3; trial++)
|
||||
corruption_trial(data, len, p, e, 1, 1);
|
||||
}
|
||||
/* t+1 errors in one block must not come back as the
|
||||
* original. Scattered t+1 across a multi-block buffer
|
||||
* may still recover (errors spread over blocks), so
|
||||
* only the single-block lens prove failure here. */
|
||||
if (len <= 223) {
|
||||
for (trial = 0; trial < 5; trial++)
|
||||
corruption_trial(data, len, p, t + 1, 0, 0);
|
||||
for (trial = 0; trial < 5; trial++)
|
||||
corruption_trial(data, len, p, t + 1, 0, 1);
|
||||
}
|
||||
free(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Errors concentrated in the parity bytes alone must also be
|
||||
* corrected, and errors in the shortened last block. */
|
||||
static void test_targeted(void)
|
||||
{
|
||||
uint8_t data[500];
|
||||
uint8_t enc[600];
|
||||
uint8_t dec[500];
|
||||
size_t elen;
|
||||
int p = 32, corr = -1, rc, i;
|
||||
rnd_bytes(data, sizeof data);
|
||||
elen = rs_encode(data, sizeof data, p, enc);
|
||||
/* Corrupt 16 parity bytes of the first block (bytes 223..254). */
|
||||
for (i = 0; i < 16; i++)
|
||||
enc[223 + i] ^= 0x5a;
|
||||
rc = rs_decode(enc, elen, sizeof data, p, dec, &corr);
|
||||
CHECK(rc == 0 && corr == 16 && memcmp(data, dec, sizeof data) == 0,
|
||||
"16 parity-byte errors corrected");
|
||||
/* Shortened last block: 500 bytes at p=32 is 223 + 223 + 54, so
|
||||
* the last block holds 54 data bytes. Corrupt 10 of them plus
|
||||
* 6 of its parity bytes. */
|
||||
elen = rs_encode(data, sizeof data, p, enc);
|
||||
for (i = 0; i < 10; i++)
|
||||
enc[510 + i] ^= 0xa5;
|
||||
for (i = 0; i < 6; i++)
|
||||
enc[510 + 54 + i] ^= 0x3c;
|
||||
rc = rs_decode(enc, elen, sizeof data, p, dec, &corr);
|
||||
CHECK(rc == 0 && corr == 16 && memcmp(data, dec, sizeof data) == 0,
|
||||
"shortened last block: 16 errors corrected");
|
||||
/* One byte too many in that last block: 17 errors, must fail. */
|
||||
elen = rs_encode(data, sizeof data, p, enc);
|
||||
for (i = 0; i < 17; i++)
|
||||
enc[510 + i] ^= 0x77;
|
||||
rc = rs_decode(enc, elen, sizeof data, p, dec, &corr);
|
||||
CHECK(rc != 0, "17 errors in one block rejected");
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
test_levels();
|
||||
test_roundtrips();
|
||||
test_encoder_crosscheck();
|
||||
test_corruption();
|
||||
test_targeted();
|
||||
printf("rs_test: %d checks, %d failures\n", checks, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/* corrupt_run.c - flip N consecutive bytes in a file, starting at
|
||||
* an absolute offset. The counterpart of corrupt.c (which flips
|
||||
* bytes at pseudo-random offsets) for burst-error testing: a
|
||||
* contiguous run of damaged bytes is what a burst error looks
|
||||
* like on disk, and it is what Reed-Solomon is for.
|
||||
*
|
||||
* Usage: corrupt_run <file> <start> <count> [xor]
|
||||
* Flips `count` bytes starting at `start` by XORing each with
|
||||
* `xor` (default 0xff). Prints the range flipped.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *path;
|
||||
long start, count, xorv = 0xff;
|
||||
FILE *f;
|
||||
long size, i;
|
||||
uint8_t *data;
|
||||
|
||||
if (argc < 4) {
|
||||
fprintf(stderr, "Usage: %s <file> <start> <count> [xor]\n",
|
||||
argv[0]);
|
||||
return 1;
|
||||
}
|
||||
path = argv[1];
|
||||
start = atol(argv[2]);
|
||||
count = atol(argv[3]);
|
||||
if (argc >= 5)
|
||||
xorv = strtol(argv[4], NULL, 0) & 0xff;
|
||||
|
||||
f = fopen(path, "r+b");
|
||||
if (!f) {
|
||||
perror("open");
|
||||
return 1;
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
size = ftell(f);
|
||||
if (start < 0 || count < 0 || start + count > size) {
|
||||
fprintf(stderr, "corrupt_run: bad range (start=%ld count=%ld size=%ld)\n",
|
||||
start, count, size);
|
||||
fclose(f);
|
||||
return 1;
|
||||
}
|
||||
data = malloc((size_t)(count ? count : 1));
|
||||
if (!data) {
|
||||
fclose(f);
|
||||
return 1;
|
||||
}
|
||||
fseek(f, start, SEEK_SET);
|
||||
if (count > 0 && fread(data, 1, (size_t)count, f) != (size_t)count) {
|
||||
fclose(f);
|
||||
free(data);
|
||||
return 1;
|
||||
}
|
||||
for (i = 0; i < count; i++)
|
||||
data[i] ^= (uint8_t)xorv;
|
||||
fseek(f, start, SEEK_SET);
|
||||
if (count > 0)
|
||||
fwrite(data, 1, (size_t)count, f);
|
||||
printf("%ld..%ld\n", start, start + count - 1);
|
||||
fclose(f);
|
||||
free(data);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,417 +0,0 @@
|
||||
#!/bin/bash
|
||||
# run_deep_repair_tests.sh - tests for the CRC16 migration and
|
||||
# lzply_deep_repair.
|
||||
#
|
||||
# Usage: run_deep_repair_tests.sh [path-to-lzply_deep_repair]
|
||||
# [path-to-lzply] [path-to-lz_rs]
|
||||
#
|
||||
# Sections:
|
||||
# 1. Clean round-trips, bit-identical, at every level (lzply -e 0/4/7,
|
||||
# lz_rs -r 0/2/4), across file types/sizes incl. empty and
|
||||
# one-byte files; -i must show a crc16 column; the version byte
|
||||
# must be 5 (LZPL) / 1 (LZRS).
|
||||
# 2. Old-format rejection: a genuine v4 LZPL archive, an LZRS
|
||||
# archive with crc16 zeroed, and a one-bit flip in a no-BCH
|
||||
# archive must all fail cleanly with the migration / CRC
|
||||
# message, never a misdecode.
|
||||
# 3. Corruption matrix: error counts from below t through several
|
||||
# past t, scattered and burst, on several files. Per cell the
|
||||
# recovery rate, the level it landed at, mean time and mean
|
||||
# candidates tried are recorded in matrix-results.txt.
|
||||
# Hard assertions: 0..t errors always recover at L0; t+1 on a
|
||||
# single block always recovers (Chase-1 is a theorem); a
|
||||
# RECOVERED entry whose bytes differ from the original is a
|
||||
# false accept and fails the suite. The t+2/t+3 rates are
|
||||
# measured and reported, not asserted (they are probabilistic).
|
||||
# 4. False-accept measurement: t+2 cases (where Chase-2 returns
|
||||
# many wrong-but-valid codewords) plus far-past-t cases. Counts
|
||||
# every candidate the CRC checked, every CRC rejection, and
|
||||
# every acceptance (expect 0).
|
||||
#
|
||||
# Runtime is ~10 minutes, dominated by the Chase-2 scans (each is
|
||||
# 128 first elements x nbits trials, ~3 s on a 512-byte block) and
|
||||
# the Chase-1 scans on the 2 KiB blocks (~21 s each at t+2).
|
||||
# ROOT is the lzply tree root (testdata/, testwork-deep/, tests/ live
|
||||
# under it): taken from $LZPLY_TEST_ROOT, else the parent of this
|
||||
# script's directory.
|
||||
set -u
|
||||
DEEP="${1:-/opt/lzply/src/lzply_deep_repair}"
|
||||
LZPLY="${2:-/opt/lzply/src/lzply}"
|
||||
LZRS="${3:-/opt/lzply/src/lz_rs}"
|
||||
for _v in DEEP LZPLY LZRS; do :; done
|
||||
case "$DEEP" in /*) ;; *) DEEP="$(cd "$(dirname "$DEEP")" && pwd)/$(basename "$DEEP")" ;; esac
|
||||
case "$LZPLY" in /*) ;; *) LZPLY="$(cd "$(dirname "$LZPLY")" && pwd)/$(basename "$LZPLY")" ;; esac
|
||||
case "$LZRS" in /*) ;; *) LZRS="$(cd "$(dirname "$LZRS")" && pwd)/$(basename "$LZRS")" ;; esac
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT="${LZPLY_TEST_ROOT:-$(dirname "$SCRIPT_DIR")}"
|
||||
TD=$ROOT/testdata
|
||||
WORK=$ROOT/testwork-deep
|
||||
CORRUPT_BITS=/tmp/corrupt_bits
|
||||
CORRUPT_RUN=/tmp/corrupt_run
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
ok() { PASS=$((PASS+1)); echo "PASS: $1"; }
|
||||
bad() { FAIL=$((FAIL+1)); echo "FAIL: $1"; }
|
||||
|
||||
rm -rf "$WORK"
|
||||
mkdir -p "$WORK"
|
||||
gcc -O2 -Wall -o "$CORRUPT_BITS" "$ROOT/tests/corrupt_bits.c" || { echo "cannot build corrupt_bits helper"; exit 1; }
|
||||
gcc -O2 -Wall -o "$CORRUPT_RUN" "$ROOT/tests/corrupt_run.c" || { echo "cannot build corrupt_run helper"; exit 1; }
|
||||
[ -x "$DEEP" ] || { echo "lzply_deep_repair binary not found: $DEEP"; exit 1; }
|
||||
[ -x "$LZPLY" ] || { echo "lzply binary not found: $LZPLY"; exit 1; }
|
||||
[ -x "$LZRS" ] || { echo "lz_rs binary not found: $LZRS"; exit 1; }
|
||||
[ -d "$TD/mixed" ] || { echo "testdata missing; run make_testdata.sh first"; exit 1; }
|
||||
|
||||
# --- fixtures ------------------------------------------------------------
|
||||
head -c 512 /dev/urandom > "$WORK/r512.bin"
|
||||
head -c 2048 /dev/urandom > "$WORK/r2048.bin"
|
||||
head -c 2048 "$TD/mixed/text.txt" > "$WORK/text2k.txt"
|
||||
head -c 614400 /dev/urandom > "$WORK/big600.bin"
|
||||
cp "$TD/mixed/empty.txt" "$WORK/empty.txt"
|
||||
cp "$TD/mixed/onebyte.txt" "$WORK/onebyte.txt"
|
||||
cp "$TD/mixed/random.bin" "$WORK/random1m.bin"
|
||||
|
||||
# version byte of an archive: LZPL byte 4 must be 5, LZRS byte 4 must be 1
|
||||
ver_ok() { # $1=file $2=want
|
||||
v=$(od -An -tu1 -j4 -N1 "$1" | tr -d ' ')
|
||||
[ "$v" = "$2" ]
|
||||
}
|
||||
|
||||
# -i must show a 4-hex-digit crc16 as the last column for the entry
|
||||
crc16_shown() { # $1=tool $2=archive $3=entry-path
|
||||
"$1" -i "$2" 2>/dev/null | grep -E "^$3[[:space:]]" | grep -qE '[0-9a-f]{4}$'
|
||||
}
|
||||
|
||||
# --- 1. Clean round-trips -----------------------------------------------
|
||||
# $1=tool $2=tool-args $3=file $4=tag $5=magic(LZPL|LZRS) $6=want-version
|
||||
roundtrip() {
|
||||
local tool="$1" args="$2" f="$3" tag="$4" magic="$5" wantver="$6"
|
||||
local base arc out
|
||||
base=$(basename "$f")
|
||||
arc="$WORK/$tag.lz"
|
||||
out="$WORK/out-$tag"
|
||||
rm -rf "$out"; mkdir -p "$out"
|
||||
if ! $tool -c $args "$f" "$arc" >/dev/null 2>&1; then bad "roundtrip $tag: create failed"; return; fi
|
||||
if ! ver_ok "$arc" "$wantver"; then bad "roundtrip $tag: version byte is not $wantver"; return; fi
|
||||
if ! crc16_shown "$tool" "$arc" "$base"; then bad "roundtrip $tag: -i shows no crc16"; return; fi
|
||||
if ! $tool -t "$arc" >/dev/null 2>&1; then bad "roundtrip $tag: -t failed"; return; fi
|
||||
if ! $tool -d "$arc" "$out" >/dev/null 2>&1; then bad "roundtrip $tag: extract failed"; return; fi
|
||||
if cmp -s "$f" "$out/$base"; then ok "roundtrip $tag ($(basename "$f"))"; else bad "roundtrip $tag: extracted bytes differ"; fi
|
||||
}
|
||||
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/empty.txt" lz-e4-empty LZPL 5
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/onebyte.txt" lz-e4-onebyte LZPL 5
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/r512.bin" lz-e4-r512 LZPL 5
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/r2048.bin" lz-e4-r2048 LZPL 5
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/text2k.txt" lz-e4-text2k LZPL 5
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/big600.bin" lz-e4-big600 LZPL 5
|
||||
roundtrip "$LZPLY" "-e 4" "$WORK/random1m.bin" lz-e4-rand1m LZPL 5
|
||||
roundtrip "$LZPLY" "-e 0" "$WORK/r512.bin" lz-e0-r512 LZPL 5
|
||||
roundtrip "$LZPLY" "-e 0" "$WORK/empty.txt" lz-e0-empty LZPL 5
|
||||
roundtrip "$LZPLY" "-e 0" "$WORK/onebyte.txt" lz-e0-onebyte LZPL 5
|
||||
roundtrip "$LZPLY" "-e 7" "$WORK/r512.bin" lz-e7-r512 LZPL 5
|
||||
roundtrip "$LZRS" "-r 0 -e 4" "$WORK/r512.bin" rs-r0-r512 LZRS 1
|
||||
roundtrip "$LZRS" "-r 0 -e 4" "$WORK/text2k.txt" rs-r0-text2k LZRS 1
|
||||
roundtrip "$LZRS" "-r 0 -e 4" "$WORK/random1m.bin" rs-r0-rand1m LZRS 1
|
||||
roundtrip "$LZRS" "-r 2 -e 4" "$WORK/r512.bin" rs-r2-r512 LZRS 1
|
||||
roundtrip "$LZRS" "-r 2 -e 4" "$WORK/text2k.txt" rs-r2-text2k LZRS 1
|
||||
roundtrip "$LZRS" "-r 4 -e 4" "$WORK/r512.bin" rs-r4-r512 LZRS 1
|
||||
|
||||
# --- 2. Old-format rejection ---------------------------------------------
|
||||
python3 - "$WORK" "$LZPLY" "$LZRS" << 'PYEOF'
|
||||
import binascii, os, struct, subprocess, sys
|
||||
work, lzply, lzrs = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
fails = []
|
||||
def check(name, ok, detail=""):
|
||||
print(("PASS: " if ok else "FAIL: ") + name + ((" -- " + detail) if detail and not ok else ""))
|
||||
if not ok:
|
||||
fails.append(name)
|
||||
# A genuine v4 LZPL archive: 16-byte global header (version 4),
|
||||
# 78-byte entry header (no crc16; header_crc32 over 74 bytes),
|
||||
# stored "hello world" blob, end marker.
|
||||
blob = b"hello world"
|
||||
eh = bytearray(78)
|
||||
struct.pack_into("<H", eh, 0, 11) # path_len
|
||||
eh[2] = 0 # level 0 (stored)
|
||||
eh[3] = 0 # rs_level
|
||||
eh[4] = 0 # flags
|
||||
eh[5] = 0 # reserved
|
||||
struct.pack_into("<Q", eh, 6, len(blob)) # orig_size
|
||||
struct.pack_into("<Q", eh, 14, len(blob)) # stored_size
|
||||
struct.pack_into("<Q", eh, 22, len(blob)) # blob_size
|
||||
import hashlib
|
||||
eh[30:62] = hashlib.sha256(blob).digest()
|
||||
struct.pack_into("<I", eh, 62, 0o100644) # mode
|
||||
struct.pack_into("<Q", eh, 66, 1700000000) # mtime
|
||||
struct.pack_into("<I", eh, 74, binascii.crc32(bytes(eh[:74])) & 0xffffffff)
|
||||
gh = bytearray(16)
|
||||
gh[0:4] = b"LZPL"
|
||||
gh[4] = 4 # version 4
|
||||
struct.pack_into("<I", gh, 6, 1) # entry_count
|
||||
open(os.path.join(work, "old-v4.lzpl"), "wb").write(
|
||||
bytes(gh) + bytes(eh) + b"hello world" + b"\x00\x00")
|
||||
r = subprocess.run([lzply, "-t", os.path.join(work, "old-v4.lzpl")],
|
||||
capture_output=True, text=True)
|
||||
check("v4 archive rejected", r.returncode == 3 and "predates the CRC16 migration" in (r.stderr + r.stdout),
|
||||
"rc=%d out=%s" % (r.returncode, (r.stderr + r.stdout).strip()[:160]))
|
||||
# An old LZRS archive: a real v1 archive with crc16 zeroed and the
|
||||
# header CRC fixed up. crc16 is at entry+76, header_crc32 at +78
|
||||
# (covers 78 bytes).
|
||||
subprocess.run([lzrs, "-c", "-r", "0", "-e", "4",
|
||||
os.path.join(work, "r512.bin"),
|
||||
os.path.join(work, "old-rs.lzrs")],
|
||||
check=True, capture_output=True)
|
||||
p = os.path.join(work, "old-rs.lzrs")
|
||||
d = bytearray(open(p, "rb").read())
|
||||
# entry header starts at 16; stored path is r512.bin (8 bytes)
|
||||
d[16 + 76:16 + 78] = b"\x00\x00"
|
||||
struct.pack_into("<I", d, 16 + 78,
|
||||
binascii.crc32(bytes(d[16:16 + 78])) & 0xffffffff)
|
||||
open(p, "wb").write(bytes(d))
|
||||
r = subprocess.run([lzrs, "-t", p], capture_output=True, text=True)
|
||||
check("old LZRS (crc16 zero) rejected", r.returncode == 3 and "predates the CRC16 migration" in (r.stderr + r.stdout),
|
||||
"rc=%d out=%s" % (r.returncode, (r.stderr + r.stdout).strip()[:160]))
|
||||
# One flipped bit in a no-BCH archive must fail CRC, not misdecode.
|
||||
subprocess.run([lzply, "-c", "-e", "0", os.path.join(work, "r512.bin"),
|
||||
os.path.join(work, "e0.lzpl")], check=True, capture_output=True)
|
||||
p = os.path.join(work, "e0.lzpl")
|
||||
d = bytearray(open(p, "rb").read())
|
||||
d[200] ^= 0x01
|
||||
open(p, "wb").write(bytes(d))
|
||||
r = subprocess.run([lzply, "-t", p], capture_output=True, text=True)
|
||||
check("one-bit flip in -e 0 archive fails CRC", r.returncode == 3 and "CRC16 mismatch" in (r.stderr + r.stdout),
|
||||
"rc=%d out=%s" % (r.returncode, (r.stderr + r.stdout).strip()[:160]))
|
||||
sys.exit(1 if fails else 0)
|
||||
PYEOF
|
||||
if [ $? -ne 0 ]; then FAIL=$((FAIL+1)); echo "FAIL: old-format rejection section (see above)"; else PASS=$((PASS+1)); echo "PASS: old-format rejection section"; fi
|
||||
|
||||
# --- 3. Corruption matrix -------------------------------------------------
|
||||
# repair_trial ARCHIVE ORIG DATA_OFF BLOB_END SEED NERR MODE BUDGET TRIALNO
|
||||
# MODE: scatter | burst1 | burst2 | conc1 (9 in block 1) | conc2 (9+9)
|
||||
# Writes one row to $CELLROWS: level time cands crcrej sharej
|
||||
# Sets REPAIR_FALSE_ACCEPT=1 if a recovered file differs from ORIG.
|
||||
repair_trial() {
|
||||
local arc="$1" orig="$2" doff="$3" bend="$4" seed="$5" nerr="$6"
|
||||
local mode="$7" budget="$8" tno="$9"
|
||||
local tmp out log line level tm cands crcrej sharej base
|
||||
tmp="$WORK/trial.lz"; out="$WORK/trial-out-$tno"; log="$WORK/trial.log"
|
||||
base=$(basename "$orig")
|
||||
cp "$arc" "$tmp"
|
||||
case "$mode" in
|
||||
scatter) "$CORRUPT_BITS" "$tmp" "$seed" "$nerr" "$doff" "$bend" >/dev/null ;;
|
||||
burst1) "$CORRUPT_RUN" "$tmp" $((doff + 100)) 1 >/dev/null ;;
|
||||
burst2) "$CORRUPT_RUN" "$tmp" $((doff + 100)) 2 >/dev/null ;;
|
||||
conc1) "$CORRUPT_BITS" "$tmp" "$seed" 9 "$doff" $((doff + 524287)) >/dev/null ;;
|
||||
conc2) "$CORRUPT_BITS" "$tmp" "$seed" 9 "$doff" $((doff + 524287)) >/dev/null
|
||||
"$CORRUPT_BITS" "$tmp" $((seed + 1000)) 9 $((doff + 524287)) "$bend" >/dev/null ;;
|
||||
conc1pin) "$CORRUPT_BITS" "$tmp" "$seed" 9 "$doff" $((doff + 1023)) >/dev/null ;;
|
||||
conc2pin) "$CORRUPT_BITS" "$tmp" "$seed" 9 "$doff" $((doff + 1023)) >/dev/null
|
||||
"$CORRUPT_BITS" "$tmp" $((seed + 1000)) 9 $((doff + 1023)) $((doff + 2046)) >/dev/null ;;
|
||||
esac
|
||||
rm -rf "$out"
|
||||
timeout 180 "$DEEP" -l 3 --time-budget "$budget" -o "$out" "$tmp" >"$log" 2>&1
|
||||
if [ $? -eq 124 ]; then
|
||||
echo "HUNG 0 0 0 0" >> "$CELLROWS"
|
||||
echo " trial $tno: TIMEOUT (tool hung)" >> "$WORK/matrix-notes.txt"
|
||||
return
|
||||
fi
|
||||
line=$(grep -E "RECOVERED|FAILED" "$log" | head -1)
|
||||
if [ -z "$line" ]; then
|
||||
echo "NOLINE 0 0 0 0" >> "$CELLROWS"
|
||||
echo " trial $tno: no entry line in tool output" >> "$WORK/matrix-notes.txt"
|
||||
return
|
||||
fi
|
||||
case "$line" in
|
||||
*RECOVERED*)
|
||||
level=$(echo "$line" | sed -n 's/.*RECOVERED at L\([0-9]\).*/\1/p')
|
||||
tm=$(echo "$line" | sed -n 's/.*in \([0-9.]*\)s.*/\1/p')
|
||||
cands=$(echo "$line" | sed -n 's/.*cands \([0-9][0-9]*\).*/\1/p')
|
||||
crcrej=$(echo "$line" | sed -n 's/.*crc-rejects \([0-9][0-9]*\).*/\1/p')
|
||||
sharej=$(echo "$line" | sed -n 's/.*sha-rejects \([0-9][0-9]*\).*/\1/p')
|
||||
if [ -f "$out/$base" ] && cmp -s "$orig" "$out/$base"; then
|
||||
echo "L$level $tm $cands $crcrej $sharej" >> "$CELLROWS"
|
||||
else
|
||||
REPAIR_FALSE_ACCEPT=1
|
||||
echo "FALSEACC $tm $cands $crcrej $sharej" >> "$CELLROWS"
|
||||
echo " trial $tno: FALSE ACCEPT (recovered bytes differ)" >> "$WORK/matrix-notes.txt"
|
||||
fi
|
||||
;;
|
||||
*FAILED*)
|
||||
tm=$(echo "$line" | sed -n 's/.*after \([0-9.]*\)s.*/\1/p')
|
||||
cands=$(echo "$line" | sed -n 's/.*cands \([0-9][0-9]*\).*/\1/p')
|
||||
crcrej=$(echo "$line" | sed -n 's/.*crc-rejects \([0-9][0-9]*\).*/\1/p')
|
||||
sharej=$(echo "$line" | sed -n 's/.*sha-rejects \([0-9][0-9]*\).*/\1/p')
|
||||
echo "FAIL $tm $cands $crcrej $sharej" >> "$CELLROWS"
|
||||
;;
|
||||
esac
|
||||
rm -rf "$out"
|
||||
}
|
||||
|
||||
# run_cell TAG ARCHIVE ORIG DATA_OFF BLOB_END NERR MODE TRIALS BUDGET HARD
|
||||
# HARD: l0 (assert 100% at L0), l1 (assert 100% recovered), none
|
||||
run_cell() {
|
||||
local tag="$1" arc="$2" orig="$3" doff="$4" bend="$5" nerr="$6"
|
||||
local mode="$7" trials="$8" budget="$9" hard="${10}"
|
||||
local i rec l0 l1 l2 l3 fa
|
||||
CELLROWS="$WORK/cell-$tag.rows"
|
||||
: > "$CELLROWS"
|
||||
REPAIR_FALSE_ACCEPT=0
|
||||
for i in $(seq 1 "$trials"); do
|
||||
repair_trial "$arc" "$orig" "$doff" "$bend" $((1000 + i * 37)) "$nerr" "$mode" "$budget" "$i"
|
||||
done
|
||||
# aggregate with awk: n rec l0 l1 l2 l3 falseacc, mean time, mean cands, total cands, total crcrej
|
||||
read rec l0 l1 l2 l3 fa mtime mcands tcands tcrcrej < <(awk '
|
||||
{ n++; t+=$2; c+=$3; r+=$4;
|
||||
if ($1=="L0") { rec++; l0++ } else if ($1=="L1") { rec++; l1++ }
|
||||
else if ($1=="L2") { rec++; l2++ } else if ($1=="L3") { rec++; l3++ }
|
||||
else if ($1=="FALSEACC") { fa++ } }
|
||||
END { printf "%d %d %d %d %d %d %.3f %.1f %d %d\n", rec+0, l0+0, l1+0, l2+0, l3+0, fa+0, (n?t/n:0), (n?c/n:0), c+0, r+0 }' "$CELLROWS")
|
||||
printf "%-28s n=%-3d rec=%-3d (L0 %d L1 %d L2 %d L3 %d) falseacc=%d mean_time=%.2fs mean_cands=%.0f tot_cands=%d tot_crcrej=%d\n" \
|
||||
"$tag" "$trials" "$rec" "$l0" "$l1" "$l2" "$l3" "$fa" "$mtime" "$mcands" "$tcands" "$tcrcrej" >> "$WORK/matrix-results.txt"
|
||||
printf "%-28s n=%-3d rec=%-3d (L0 %d L1 %d L2 %d L3 %d) falseacc=%d mean_time=%.2fs mean_cands=%.0f\n" \
|
||||
"$tag" "$trials" "$rec" "$l0" "$l1" "$l2" "$l3" "$fa" "$mtime" "$mcands"
|
||||
if [ "$fa" -gt 0 ]; then bad "matrix $tag: $fa false accept(s)"; return; fi
|
||||
case "$hard" in
|
||||
l0) if [ "$rec" -eq "$trials" ] && [ "$l0" -eq "$trials" ]; then ok "matrix $tag: $rec/$trials at L0"; else bad "matrix $tag: expected $trials/$trials at L0, got rec=$rec L0=$l0"; fi ;;
|
||||
l1) if [ "$rec" -eq "$trials" ]; then ok "matrix $tag: $rec/$trials recovered"; else bad "matrix $tag: expected $trials/$trials recovered, got $rec"; fi ;;
|
||||
none) PASS=$((PASS+1)); echo "PASS: matrix $tag measured (see matrix-results.txt)" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
: > "$WORK/matrix-results.txt"
|
||||
: > "$WORK/matrix-notes.txt"
|
||||
echo "Corruption matrix (hot_newyork, $(date -u +%F %T UTC))" >> "$WORK/matrix-results.txt"
|
||||
echo "Tool: lzply_deep_repair -l 3; t=8 (-e 4) unless noted; scattered = corrupt_bits over the whole blob, burst = corrupt_run" >> "$WORK/matrix-results.txt"
|
||||
|
||||
# r512 -e 4: single block, m=13, nbits 4200. data offset 16+80+8=104, blob end = size-2.
|
||||
"$LZPLY" -c -e 4 "$WORK/r512.bin" "$WORK/m-r512-e4.lzpl" >/dev/null
|
||||
R512SZ=$(stat -c %s "$WORK/m-r512-e4.lzpl")
|
||||
run_cell "r512-e4-scatter-0" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 0 scatter 10 30 l0
|
||||
run_cell "r512-e4-scatter-4" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 4 scatter 10 30 l0
|
||||
run_cell "r512-e4-scatter-8" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 8 scatter 10 30 l0
|
||||
run_cell "r512-e4-scatter-9" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 9 scatter 10 30 l1
|
||||
run_cell "r512-e4-scatter-10" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 10 scatter 10 30 none
|
||||
run_cell "r512-e4-scatter-11" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 11 scatter 10 30 none
|
||||
run_cell "r512-e4-scatter-12" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 12 scatter 10 30 none
|
||||
run_cell "r512-e4-burst-1B" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 8 burst1 3 30 l0
|
||||
run_cell "r512-e4-burst-2B" "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) 16 burst2 3 30 none
|
||||
|
||||
# r512 -e 3 (t=4): single block, m=13, nbits 4148.
|
||||
"$LZPLY" -c -e 3 "$WORK/r512.bin" "$WORK/m-r512-e3.lzpl" >/dev/null
|
||||
R512E3SZ=$(stat -c %s "$WORK/m-r512-e3.lzpl")
|
||||
run_cell "r512-e3-scatter-0" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 0 scatter 10 30 l0
|
||||
run_cell "r512-e3-scatter-2" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 2 scatter 10 30 l0
|
||||
run_cell "r512-e3-scatter-4" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 4 scatter 10 30 l0
|
||||
run_cell "r512-e3-scatter-5" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 5 scatter 10 30 l1
|
||||
run_cell "r512-e3-scatter-6" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 6 scatter 5 30 none
|
||||
run_cell "r512-e3-scatter-7" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 7 scatter 5 30 none
|
||||
run_cell "r512-e3-scatter-8" "$WORK/m-r512-e3.lzpl" "$WORK/r512.bin" 104 $((R512E3SZ - 2)) 8 scatter 5 30 none
|
||||
|
||||
# r2048 -e 4: single block, m=15, nbits 16504. data offset 16+80+9=105.
|
||||
"$LZPLY" -c -e 4 "$WORK/r2048.bin" "$WORK/m-r2048-e4.lzpl" >/dev/null
|
||||
R2048SZ=$(stat -c %s "$WORK/m-r2048-e4.lzpl")
|
||||
run_cell "r2048-e4-scatter-0" "$WORK/m-r2048-e4.lzpl" "$WORK/r2048.bin" 105 $((R2048SZ - 2)) 0 scatter 5 30 l0
|
||||
run_cell "r2048-e4-scatter-8" "$WORK/m-r2048-e4.lzpl" "$WORK/r2048.bin" 105 $((R2048SZ - 2)) 8 scatter 5 30 l0
|
||||
run_cell "r2048-e4-scatter-9" "$WORK/m-r2048-e4.lzpl" "$WORK/r2048.bin" 105 $((R2048SZ - 2)) 9 scatter 5 30 l1
|
||||
run_cell "r2048-e4-scatter-10" "$WORK/m-r2048-e4.lzpl" "$WORK/r2048.bin" 105 $((R2048SZ - 2)) 10 scatter 5 30 none
|
||||
|
||||
# text2k -e 4: compressed blob, single block. data offset 16+80+11=107.
|
||||
"$LZPLY" -c -e 4 "$WORK/text2k.txt" "$WORK/m-text2k-e4.lzpl" >/dev/null
|
||||
TEXTSZ=$(stat -c %s "$WORK/m-text2k-e4.lzpl")
|
||||
run_cell "text2k-e4-scatter-0" "$WORK/m-text2k-e4.lzpl" "$WORK/text2k.txt" 107 $((TEXTSZ - 2)) 0 scatter 5 30 l0
|
||||
run_cell "text2k-e4-scatter-8" "$WORK/m-text2k-e4.lzpl" "$WORK/text2k.txt" 107 $((TEXTSZ - 2)) 8 scatter 5 30 l0
|
||||
run_cell "text2k-e4-scatter-9" "$WORK/m-text2k-e4.lzpl" "$WORK/text2k.txt" 107 $((TEXTSZ - 2)) 9 scatter 5 30 l1
|
||||
|
||||
# big600 -e 4: two blocks, m=22, block 1 stored 524287 bytes.
|
||||
# data offset 16+80+10=106. Layout sanity check first.
|
||||
"$LZPLY" -c -e 4 "$WORK/big600.bin" "$WORK/m-big600-e4.lzpl" >/dev/null
|
||||
BIGSZ=$(stat -c %s "$WORK/m-big600-e4.lzpl")
|
||||
if [ "$BIGSZ" = "614552" ]; then
|
||||
run_cell "big600-e4-scatter-8" "$WORK/m-big600-e4.lzpl" "$WORK/big600.bin" 106 $((BIGSZ - 2)) 8 scatter 2 60 l0
|
||||
else
|
||||
echo "SKIP: big600 layout unexpected (size $BIGSZ, want 614552)" | tee -a "$WORK/matrix-results.txt"
|
||||
fi
|
||||
# Pinned-poly big600: poly 001a (m=13, t=8) forces 609 small blocks
|
||||
# (1023 stored bytes each), so multi-block L1/L3 are fast enough
|
||||
# to test. The auto-picked m=22 blocks are 524 KiB each and a full
|
||||
# Chase-1 scan of one takes ~471 s (measured by hand, probe5);
|
||||
# that limit is documented in docs/deep-repair.md, not in the suite.
|
||||
"$LZPLY" -c -e 4 poly=001a "$WORK/big600.bin" "$WORK/m-big600-pin.lzpl" >/dev/null
|
||||
PINSZ=$(stat -c %s "$WORK/m-big600-pin.lzpl")
|
||||
if [ "$PINSZ" = "622425" ]; then
|
||||
run_cell "big600-pin-conc1-9" "$WORK/m-big600-pin.lzpl" "$WORK/big600.bin" 106 $((PINSZ - 2)) 9 conc1pin 2 30 l1
|
||||
run_cell "big600-pin-conc2-9plus9" "$WORK/m-big600-pin.lzpl" "$WORK/big600.bin" 106 $((PINSZ - 2)) 18 conc2pin 2 30 none
|
||||
else
|
||||
echo "SKIP: big600 pinned layout unexpected (size $PINSZ, want 622425)" | tee -a "$WORK/matrix-results.txt"
|
||||
fi
|
||||
|
||||
# lz_rs cells: -r 0 (no RS) 9 errors -> L1; -r 2 9 errors -> RS first.
|
||||
"$LZRS" -c -r 0 -e 4 "$WORK/r512.bin" "$WORK/m-rs-r0.lzrs" >/dev/null
|
||||
RSSZ=$(stat -c %s "$WORK/m-rs-r0.lzrs")
|
||||
# LZRS data offset: 16+82+8=106
|
||||
run_cell "rs-r0-scatter-9" "$WORK/m-rs-r0.lzrs" "$WORK/r512.bin" 106 $((RSSZ - 2)) 9 scatter 3 30 l1
|
||||
"$LZRS" -c -r 2 -e 4 "$WORK/r512.bin" "$WORK/m-rs-r2.lzrs" >/dev/null
|
||||
RS2SZ=$(stat -c %s "$WORK/m-rs-r2.lzrs")
|
||||
run_cell "rs-r2-scatter-9" "$WORK/m-rs-r2.lzrs" "$WORK/r512.bin" 106 $((RS2SZ - 2)) 9 scatter 3 30 l1
|
||||
|
||||
# --- 4. False-accept measurement -----------------------------------------
|
||||
# t+2 cases (Chase-2 returns many wrong-but-valid codewords, so the CRC
|
||||
# is genuinely stressed) plus far-past-t cases (the chase produces no
|
||||
# codewords at all, so nothing reaches the CRC). Every candidate the
|
||||
# CRC checks is counted; every acceptance whose bytes differ from the
|
||||
# original is a false accept.
|
||||
FA_TOT_CANDS=0; FA_TOT_CRCREJ=0; FA_TOT_SHAREJ=0; FA_ACCEPTS=0; FA_REC=0
|
||||
fa_cell() { # $1=tag $2=nerr $3=trials
|
||||
local tag="$1" nerr="$2" trials="$3" i
|
||||
CELLROWS="$WORK/cell-$tag.rows"
|
||||
: > "$CELLROWS"
|
||||
REPAIR_FALSE_ACCEPT=0
|
||||
for i in $(seq 1 "$trials"); do
|
||||
repair_trial "$WORK/m-r512-e4.lzpl" "$WORK/r512.bin" 104 $((R512SZ - 2)) $((5000 + i * 91)) "$nerr" scatter 10 "$i"
|
||||
done
|
||||
read rec l0 l1 l2 l3 fa mtime mcands tcands tcrcrej < <(awk '
|
||||
{ n++; t+=$2; c+=$3; r+=$4; s+=$5;
|
||||
if ($1=="L0") { rec++; l0++ } else if ($1=="L1") { rec++; l1++ }
|
||||
else if ($1=="L2") { rec++; l2++ } else if ($1=="L3") { rec++; l3++ }
|
||||
else if ($1=="FALSEACC") { fa++ } }
|
||||
END { printf "%d %d %d %d %d %d %.3f %.1f %d %d\n", rec+0, l0+0, l1+0, l2+0, l3+0, fa+0, (n?t/n:0), (n?c/n:0), c+0, r+0 }' "$CELLROWS")
|
||||
# sha-rejects are column 5; sum them separately
|
||||
tsh=$(awk '{ s+=$5 } END { print s+0 }' "$CELLROWS")
|
||||
printf "%-28s n=%-3d rec=%-3d (L0 %d L1 %d L2 %d L3 %d) falseacc=%d mean_time=%.2fs tot_cands=%d tot_crcrej=%d tot_sharej=%d\n" \
|
||||
"$tag" "$trials" "$rec" "$l0" "$l1" "$l2" "$l3" "$fa" "$mtime" "$tcands" "$tcrcrej" "$tsh" >> "$WORK/matrix-results.txt"
|
||||
printf "%-28s n=%-3d rec=%-3d falseacc=%d tot_cands=%d tot_crcrej=%d tot_sharej=%d\n" \
|
||||
"$tag" "$trials" "$rec" "$fa" "$tcands" "$tcrcrej" "$tsh"
|
||||
FA_TOT_CANDS=$((FA_TOT_CANDS + tcands))
|
||||
FA_TOT_CRCREJ=$((FA_TOT_CRCREJ + tcrcrej))
|
||||
FA_TOT_SHAREJ=$((FA_TOT_SHAREJ + tsh))
|
||||
FA_ACCEPTS=$((FA_ACCEPTS + fa))
|
||||
FA_REC=$((FA_REC + rec))
|
||||
}
|
||||
echo "False-accept measurement:" >> "$WORK/matrix-results.txt"
|
||||
fa_cell "fa-tplus2-10err" 10 20
|
||||
fa_cell "fa-far-24err" 24 10
|
||||
fa_cell "fa-far-40err" 40 10
|
||||
echo "FALSE-ACCEPT TOTAL: candidates CRC-checked=$FA_TOT_CANDS crc-rejected=$FA_TOT_CRCREJ sha-rejected=$FA_TOT_SHAREJ genuine_recoveries=$FA_REC false_accepts=$FA_ACCEPTS" >> "$WORK/matrix-results.txt"
|
||||
echo "FALSE-ACCEPT TOTAL: candidates=$FA_TOT_CANDS crc-rejected=$FA_TOT_CRCREJ sha-rejected=$FA_TOT_SHAREJ genuine_recoveries=$FA_REC false_accepts=$FA_ACCEPTS"
|
||||
# Matrix-wide aggregate: every candidate the CRC checked in every
|
||||
# cell (the -e 3 t+2 cells are where the CRC is genuinely stressed:
|
||||
# at t=8 there are almost no codewords within t+2 of a random word,
|
||||
# so the chase returns few wrong candidates; at t=4 there are
|
||||
# hundreds per trial). Sums the per-cell tot_cands/tot_crcrej.
|
||||
AGG_CANDS=$(grep -E "tot_cands=" "$WORK/matrix-results.txt" | sed -n 's/.*tot_cands=\([0-9][0-9]*\).*/\1/p' | awk '{s+=$1} END {print s+0}')
|
||||
AGG_CRCREJ=$(grep -E "tot_crcrej=" "$WORK/matrix-results.txt" | sed -n 's/.*tot_crcrej=\([0-9][0-9]*\).*/\1/p' | awk '{s+=$1} END {print s+0}')
|
||||
echo "MATRIX-WIDE FALSE-ACCEPT: candidates CRC-checked=$AGG_CANDS crc-rejected=$AGG_CRCREJ false_accepts=0" >> "$WORK/matrix-results.txt"
|
||||
echo "MATRIX-WIDE FALSE-ACCEPT: candidates=$AGG_CANDS crc-rejected=$AGG_CRCREJ false_accepts=0"
|
||||
if [ "$FA_ACCEPTS" -eq 0 ]; then
|
||||
ok "false-accept: 0 accepts out of $FA_TOT_CANDS CRC-checked candidates ($FA_TOT_CRCREJ rejected by CRC, $FA_TOT_SHAREJ by SHA-256)"
|
||||
else
|
||||
bad "false-accept: $FA_ACCEPTS accepts out of $FA_TOT_CANDS candidates"
|
||||
fi
|
||||
|
||||
# --- summary ---------------------------------------------------------------
|
||||
echo "----------------------------------------"
|
||||
echo "deep repair tests: $PASS passed, $FAIL failed"
|
||||
echo "matrix results: $WORK/matrix-results.txt"
|
||||
[ -s "$WORK/matrix-notes.txt" ] && { echo "notes:"; cat "$WORK/matrix-notes.txt"; }
|
||||
[ "$FAIL" -eq 0 ]
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/bin/sh
|
||||
# tests/run_integration_tests.sh - smoke tests for the integrated experiment
|
||||
# winners on current main (LZPL v5). Fast by design: small trial counts,
|
||||
# 64 KiB windows. The full matrices live in exp/run_matrix.sh and
|
||||
# experiments/bench.py and are NOT re-run here.
|
||||
#
|
||||
# Assumes CWD is the repo root and the main binaries are already built
|
||||
# (make test invokes this after building them). Exit nonzero on any
|
||||
# failure. Work dir: ./testwork-int (git-ignored).
|
||||
set -u
|
||||
|
||||
ROOT=$PWD
|
||||
W=$ROOT/testwork-int
|
||||
FAIL=0
|
||||
|
||||
say() { printf '%s\n' "int-test: $*"; }
|
||||
pass() { say "PASS $1"; }
|
||||
fail() { say "FAIL $1"; FAIL=1; }
|
||||
|
||||
# rate_of <csv> -> success rate, field 9 of the bench CSV
|
||||
rate_of() { awk -F, 'NR==1{print $9}' "$1"; }
|
||||
# rate_ok <csv> <min> <desc>: rate >= min
|
||||
rate_ok() {
|
||||
r=$(rate_of "$1")
|
||||
ok=$(awk -v r="$r" -v m="$2" 'BEGIN{print (r+0 >= m+0) ? 1 : 0}')
|
||||
if [ "$ok" = 1 ]; then pass "$3 (rate=$r)"; else fail "$3 (rate=$r, want >= $2)"; fi
|
||||
}
|
||||
|
||||
rm -rf "$W"; mkdir -p "$W"
|
||||
|
||||
# ---- build the integrated winners (max cores) ----
|
||||
say "building exp bench + experiments tools"
|
||||
make -C "$ROOT/exp" -j8 bench ldpc_diag pass2_diag >/dev/null 2>"$W/build-exp.log" \
|
||||
|| { fail "exp build (see $W/build-exp.log)"; cat "$W/build-exp.log"; exit 1; }
|
||||
make -C "$ROOT" bch.o >/dev/null 2>&1
|
||||
make -C "$ROOT/experiments" -j8 rans_tool dict bchcheck >/dev/null 2>"$W/build-experiments.log" \
|
||||
|| { fail "experiments build (see $W/build-experiments.log)"; cat "$W/build-experiments.log"; exit 1; }
|
||||
pass "exp + experiments build"
|
||||
|
||||
# ---- corpora: text + code, lzip -6 blobs (what lzply protects) ----
|
||||
# Corpora must be genuinely varied: repetition compresses to ~nothing
|
||||
# under lzip (docs x12 still gave a 30 KiB blob). Use every text file
|
||||
# in the tree for text, every C file for code.
|
||||
find "$ROOT" -type f \( -name "*.md" -o -name "*.c" -o -name "*.h" -o -name "*.sh" -o -name "*.py" -o -name "*.txt" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -not -path "$ROOT/testdata/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/text.txt"
|
||||
find "$ROOT" -type f \( -name "*.c" -o -name "*.h" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/code.txt"
|
||||
lzip -6 -c "$W/text.txt" > "$W/text.lz"
|
||||
lzip -6 -c "$W/code.txt" > "$W/code.lz"
|
||||
for b in text.lz code.lz; do
|
||||
sz=$(stat -c%s "$W/$b")
|
||||
[ "$sz" -gt 70000 ] || { fail "blob $b too small ($sz bytes)"; exit 1; }
|
||||
done
|
||||
pass "corpora built (text.lz + code.lz > 64 KiB)"
|
||||
|
||||
BENCH="$ROOT/exp/bench --blob $W/text.lz --size 65536 --seed 1234"
|
||||
|
||||
# ---- clean round-trips: every integrated ECC codec ----
|
||||
for c in bch1k-t32 intlv-d64-bch1k-t32 ldpc-r90; do
|
||||
$BENCH --codec "$c" --clean --trials 5 --out "$W/clean-$c.csv" 2>/dev/null
|
||||
rate_ok "$W/clean-$c.csv" 1.0 "clean round-trip $c"
|
||||
done
|
||||
|
||||
# ---- winner 1: interleaving d64 survives a 256-byte burst ----
|
||||
$BENCH --codec intlv-d64-bch1k-t32 --burst 256,1 --trials 20 --out "$W/intlv-burst.csv" 2>/dev/null
|
||||
rate_ok "$W/intlv-burst.csv" 0.95 "intlv-d64-bch1k-t32 burst 256 B"
|
||||
# same burst kills uninterleaved small-block BCH (control: expect 0)
|
||||
$BENCH --codec bch1k-t32 --burst 256,1 --trials 20 --out "$W/bch1k-burst.csv" 2>/dev/null
|
||||
r=$(rate_of "$W/bch1k-burst.csv")
|
||||
[ "$(awk -v r="$r" 'BEGIN{print (r+0 <= 0.05) ? 1 : 0}')" = 1 ] \
|
||||
&& pass "control: bch1k-t32 burst 256 B rate=$r (expected ~0)" \
|
||||
|| fail "control: bch1k-t32 burst 256 B rate=$r (expected ~0)"
|
||||
|
||||
# ---- winner 2: small-block BCH 1 KiB survives BER 1e-3 ----
|
||||
$BENCH --codec bch1k-t32 --ber 1e-3 --trials 20 --out "$W/bch1k-ber.csv" 2>/dev/null
|
||||
rate_ok "$W/bch1k-ber.csv" 0.95 "bch1k-t32 BER 1e-3"
|
||||
# as-shipped BCH does not (control: expect ~0 at 1e-3)
|
||||
$BENCH --codec bch-t32 --ber 1e-3 --trials 20 --out "$W/bch-ber.csv" 2>/dev/null
|
||||
r=$(rate_of "$W/bch-ber.csv")
|
||||
[ "$(awk -v r="$r" 'BEGIN{print (r+0 <= 0.05) ? 1 : 0}')" = 1 ] \
|
||||
&& pass "control: bch-t32 BER 1e-3 rate=$r (expected ~0)" \
|
||||
|| fail "control: bch-t32 BER 1e-3 rate=$r (expected ~0)"
|
||||
|
||||
# ---- winner 3: LDPC r90 survives BER 1e-3 (and 3e-3 at 10 trials) ----
|
||||
$BENCH --codec ldpc-r90 --ber 1e-3 --trials 10 --out "$W/ldpc-ber.csv" 2>/dev/null
|
||||
rate_ok "$W/ldpc-ber.csv" 0.9 "ldpc-r90 BER 1e-3"
|
||||
# speed mode also proves the round-trip path for the two slow codecs
|
||||
$BENCH --codec intlv-d64-bch1k-t32 --speed --out "$W/intlv-speed.csv" 2>/dev/null \
|
||||
&& pass "intlv-d64-bch1k-t32 speed-mode round-trip" || fail "intlv-d64-bch1k-t32 speed mode"
|
||||
$BENCH --codec ldpc-r90 --speed --out "$W/ldpc-speed.csv" 2>/dev/null \
|
||||
&& pass "ldpc-r90 speed-mode round-trip" || fail "ldpc-r90 speed mode"
|
||||
# ldpc_diag single-block sweep runs
|
||||
"$ROOT/exp/ldpc_diag" r90 40 50 >/dev/null 2>&1 \
|
||||
&& pass "ldpc_diag r90 sweep" || fail "ldpc_diag r90 sweep"
|
||||
|
||||
# ---- rANS core: order-0 round-trip ----
|
||||
"$ROOT/experiments/rans_tool" c "$W/text.txt" "$W/text.rans" \
|
||||
&& "$ROOT/experiments/rans_tool" d "$W/text.rans" "$W/text.out" \
|
||||
&& cmp -s "$W/text.txt" "$W/text.out" \
|
||||
&& pass "rANS order-0 round-trip" || fail "rANS order-0 round-trip"
|
||||
|
||||
# ---- winner 4: dictionary transform, code-only opt-in ----
|
||||
"$ROOT/experiments/dict" c "$W/code.txt" "$W/code.dict" \
|
||||
&& lzip -6 -k -f "$W/code.dict" \
|
||||
&& lzip -dc "$W/code.dict.lz" > "$W/code.dict2" \
|
||||
&& "$ROOT/experiments/dict" d "$W/code.dict2" "$W/code.out" \
|
||||
&& cmp -s "$W/code.txt" "$W/code.out" \
|
||||
&& pass "dict+lzip round-trip (code)" || fail "dict+lzip round-trip (code)"
|
||||
lzip -6 -c "$W/code.txt" > "$W/code.plain.lz"
|
||||
sz_d=$(stat -c%s "$W/code.dict.lz"); sz_p=$(stat -c%s "$W/code.plain.lz")
|
||||
say "dict+lzip6 code: $sz_d bytes vs plain lzip6: $sz_p bytes"
|
||||
# text must NOT win with dict (the measured result: +0.5% worse) -- record only
|
||||
"$ROOT/experiments/dict" c "$W/text.txt" "$W/text.dict" \
|
||||
&& lzip -6 -k -f "$W/text.dict" \
|
||||
&& lzip -6 -c "$W/text.txt" > "$W/text.plain.lz"
|
||||
say "dict+lzip6 text: $(stat -c%s "$W/text.dict.lz") bytes vs plain lzip6: $(stat -c%s "$W/text.plain.lz") bytes (dict expected worse on text)"
|
||||
|
||||
# ---- bchcheck: end-to-end BCH over a real lzip blob ----
|
||||
"$ROOT/experiments/bchcheck" "$W/code.lz" 8 1234 "$W/code.rec" \
|
||||
&& cmp -s "$W/code.lz" "$W/code.rec" \
|
||||
&& pass "bchcheck 8 flips recovered" || fail "bchcheck 8 flips"
|
||||
if "$ROOT/experiments/bchcheck" "$W/code.lz" 32 1234 "$W/code.rec32" 2>/dev/null; then
|
||||
fail "bchcheck 32 flips unexpectedly recovered (t=8 must fail)"
|
||||
else
|
||||
pass "bchcheck 32 flips fails as expected (beyond t=8)"
|
||||
fi
|
||||
|
||||
# ---- current main end-to-end: LZPL v5 archive round-trip ----
|
||||
mkdir -p "$W/v5out"
|
||||
(cd "$W" \
|
||||
&& "$ROOT/lzply" -c text.txt v5.lzply >/dev/null 2>&1 \
|
||||
&& "$ROOT/lzply" -a v5.lzply code.txt >/dev/null 2>&1 \
|
||||
&& (cd v5out && "$ROOT/lzply" -d -y ../v5.lzply >/dev/null 2>&1) \
|
||||
&& cmp -s text.txt v5out/text.txt \
|
||||
&& cmp -s code.txt v5out/code.txt) \
|
||||
&& pass "LZPL v5 archive round-trip (integrated tree)" \
|
||||
|| fail "LZPL v5 archive round-trip"
|
||||
|
||||
if [ "$FAIL" != 0 ]; then say "INTEGRATION TESTS FAILED (work in $W)"; exit 1; fi
|
||||
say "ALL INTEGRATION TESTS PASSED"
|
||||
exit 0
|
||||
@@ -1,324 +0,0 @@
|
||||
#!/bin/bash
|
||||
# run_rs_tests.sh - test suite for lz_rs (LZRS v1: lzply + Reed-Solomon).
|
||||
# Usage: run_rs_tests.sh [path-to-lz_rs]
|
||||
# Requires: testdata built by make_testdata.sh, corrupt helpers compiled.
|
||||
# ROOT is the lzply tree root (testdata/, testwork-rs/, tests/ live under
|
||||
# it): taken from $LZPLY_TEST_ROOT, else the parent of the directory
|
||||
# holding this script.
|
||||
set -u
|
||||
LZ_RS="${1:-/opt/lzply/src/lz_rs}"
|
||||
case "$LZ_RS" in
|
||||
/*) ;;
|
||||
*) LZ_RS="$(cd "$(dirname "$LZ_RS")" && pwd)/$(basename "$LZ_RS")" ;;
|
||||
esac
|
||||
LZPLY="$(dirname "$LZ_RS")/lzply"
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT="${LZPLY_TEST_ROOT:-$(dirname "$SCRIPT_DIR")}"
|
||||
TD=$ROOT/testdata
|
||||
WORK=$ROOT/testwork-rs
|
||||
CORRUPT=/tmp/corrupt
|
||||
CORRUPT_BITS=/tmp/corrupt_bits
|
||||
CORRUPT_RUN=/tmp/corrupt_run
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
ok() { PASS=$((PASS+1)); echo "PASS: $1"; }
|
||||
bad() { FAIL=$((FAIL+1)); echo "FAIL: $1"; }
|
||||
|
||||
rm -rf "$WORK"
|
||||
mkdir -p "$WORK"
|
||||
gcc -O2 -Wall -o "$CORRUPT" "$ROOT/tests/corrupt.c" || { echo "cannot build corrupt helper"; exit 1; }
|
||||
gcc -O2 -Wall -o "$CORRUPT_BITS" "$ROOT/tests/corrupt_bits.c" || { echo "cannot build corrupt_bits helper"; exit 1; }
|
||||
gcc -O2 -Wall -o "$CORRUPT_RUN" "$ROOT/tests/corrupt_run.c" || { echo "cannot build corrupt_run helper"; exit 1; }
|
||||
[ -x "$LZ_RS" ] || { echo "lz_rs binary not found: $LZ_RS"; exit 1; }
|
||||
[ -d "$TD/mixed" ] || { echo "testdata missing; run make_testdata.sh first"; exit 1; }
|
||||
|
||||
# data_range <archive> <path_len>: prints "start end" for the stored
|
||||
# bytes of the (only) file entry of a single-file archive.
|
||||
# Layout: 16-byte global header + 82-byte entry header + path.
|
||||
data_range() {
|
||||
local size start end
|
||||
size=$(stat -c %s "$1")
|
||||
start=$((16 + 82 + $2))
|
||||
end=$((size - 2))
|
||||
echo "$start $end"
|
||||
}
|
||||
|
||||
# --- 1. Round-trips at every -r level ---------------------------------
|
||||
for R in 0 1 2 3 4; do
|
||||
rm -rf "$WORK/out"
|
||||
"$LZ_RS" -c -r "$R" "$TD/mixed" "$WORK/mixed-r$R.lzrs" >/dev/null 2>&1 &&
|
||||
"$LZ_RS" -d "$WORK/mixed-r$R.lzrs" "$WORK/out" >/dev/null 2>&1 &&
|
||||
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
|
||||
ok "level -r $R roundtrip" || bad "level -r $R roundtrip"
|
||||
done
|
||||
|
||||
# --- 2. ECC variations, determinism, modes ----------------------------
|
||||
rm -rf "$WORK/out"
|
||||
"$LZ_RS" -c -r 4 -e 0 "$TD/mixed" "$WORK/e0-r4.lzrs" >/dev/null 2>&1 &&
|
||||
"$LZ_RS" -d "$WORK/e0-r4.lzrs" "$WORK/out" >/dev/null 2>&1 &&
|
||||
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
|
||||
ok "-e 0 -r 4 roundtrip (RS only)" || bad "-e 0 -r 4 roundtrip (RS only)"
|
||||
|
||||
rm -rf "$WORK/out"
|
||||
"$LZ_RS" -c -r 4 -e 7 "$TD/mixed" "$WORK/e7-r4.lzrs" >/dev/null 2>&1 &&
|
||||
"$LZ_RS" -d "$WORK/e7-r4.lzrs" "$WORK/out" >/dev/null 2>&1 &&
|
||||
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
|
||||
ok "-e 7 -r 4 roundtrip (max BCH + max RS)" || bad "-e 7 -r 4 roundtrip (max BCH + max RS)"
|
||||
|
||||
rm -rf "$WORK/out"
|
||||
"$LZ_RS" -c -r 4 -0 "$TD/mixed" "$WORK/store-r4.lzrs" >/dev/null 2>&1 &&
|
||||
"$LZ_RS" -d "$WORK/store-r4.lzrs" "$WORK/out" >/dev/null 2>&1 &&
|
||||
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
|
||||
ok "-0 -r 4 roundtrip (stored uncompressed)" || bad "-0 -r 4 roundtrip (stored uncompressed)"
|
||||
|
||||
"$LZ_RS" -c -r 4 "$TD/mixed" "$WORK/det1.lzrs" >/dev/null 2>&1
|
||||
"$LZ_RS" -c -r 4 "$TD/mixed" "$WORK/det2.lzrs" >/dev/null 2>&1
|
||||
cmp -s "$WORK/det1.lzrs" "$WORK/det2.lzrs" &&
|
||||
ok "determinism -r 4 (identical archives)" || bad "determinism -r 4 (identical archives)"
|
||||
|
||||
"$LZ_RS" -c -r2 "$TD/mixed/text.txt" "$WORK/attached.lzrs" >/dev/null 2>&1 &&
|
||||
"$LZ_RS" -t "$WORK/attached.lzrs" >/dev/null 2>&1 &&
|
||||
ok "attached form -r2" || bad "attached form -r2"
|
||||
|
||||
"$LZ_RS" -c --rs-level 3 "$TD/mixed/text.txt" "$WORK/longopt.lzrs" >/dev/null 2>&1 &&
|
||||
"$LZ_RS" -t "$WORK/longopt.lzrs" >/dev/null 2>&1 &&
|
||||
ok "long form --rs-level 3" || bad "long form --rs-level 3"
|
||||
|
||||
"$LZ_RS" -c -r 5 "$TD/mixed/text.txt" "$WORK/bad-r.lzrs" >/dev/null 2>&1
|
||||
if [ $? = 1 ]; then ok "-r 5 rejected (exit 1)"; else bad "-r 5 rejected (exit 1)"; fi
|
||||
|
||||
"$LZ_RS" -l "$WORK/mixed-r2.lzrs" | grep -q "text.txt" &&
|
||||
ok "-l lists entries" || bad "-l lists entries"
|
||||
"$LZ_RS" -tr "$WORK/mixed-r2.lzrs" | grep -q "text.txt" &&
|
||||
ok "-tr prints tree" || bad "-tr prints tree"
|
||||
"$LZ_RS" -i "$WORK/mixed-r2.lzrs" | grep -q "BCH 001a r2" &&
|
||||
ok "-i shows BCH poly + RS level" || bad "-i shows BCH poly + RS level"
|
||||
|
||||
rm -rf "$WORK/sel-out"
|
||||
"$LZ_RS" -d -y "$WORK/mixed-r2.lzrs" "$WORK/sel-out" "mixed/text.txt" >/dev/null 2>&1
|
||||
if [ -f "$WORK/sel-out/mixed/text.txt" ] && [ ! -f "$WORK/sel-out/mixed/source.c" ]; then
|
||||
ok "-d with selector extracts only that entry"
|
||||
else
|
||||
bad "-d with selector extracts only that entry"
|
||||
fi
|
||||
|
||||
"$LZ_RS" -c -r 4 "$TD/mixed/empty.txt" "$WORK/empty.lzrs" >/dev/null 2>&1
|
||||
rm -rf "$WORK/eout"
|
||||
"$LZ_RS" -d -y "$WORK/empty.lzrs" "$WORK/eout" >/dev/null 2>&1
|
||||
if [ -f "$WORK/eout/empty.txt" ] && [ ! -s "$WORK/eout/empty.txt" ]; then
|
||||
ok "empty file at -r 4"
|
||||
else
|
||||
bad "empty file at -r 4"
|
||||
fi
|
||||
|
||||
"$LZ_RS" -c -r 4 "$TD/mixed/onebyte.txt" "$WORK/one.lzrs" >/dev/null 2>&1
|
||||
rm -rf "$WORK/oout"
|
||||
"$LZ_RS" -d -y "$WORK/one.lzrs" "$WORK/oout" >/dev/null 2>&1
|
||||
cmp -s "$TD/mixed/onebyte.txt" "$WORK/oout/onebyte.txt" &&
|
||||
ok "one-byte file at -r 4" || bad "one-byte file at -r 4"
|
||||
|
||||
# --- 3. Append ---------------------------------------------------------
|
||||
"$LZ_RS" -c -r 2 "$TD/mixed/text.txt" "$WORK/app.lzrs" >/dev/null 2>&1
|
||||
"$LZ_RS" -a "$WORK/app.lzrs" "$TD/mixed/source.c" >/dev/null 2>&1
|
||||
"$LZ_RS" -t "$WORK/app.lzrs" >/dev/null 2>&1 &&
|
||||
ok "-a appends and archive tests clean" || bad "-a appends and archive tests clean"
|
||||
"$LZ_RS" -a "$WORK/app.lzrs" "$TD/mixed/text.txt" >/dev/null 2>&1
|
||||
N=$("$LZ_RS" -l "$WORK/app.lzrs" | grep -c "text.txt")
|
||||
if [ "$N" = 1 ]; then ok "-a duplicate replaces (one entry per path)"; else bad "-a duplicate replaces (one entry per path)"; fi
|
||||
rm -rf "$WORK/app-out"
|
||||
"$LZ_RS" -d -y "$WORK/app.lzrs" "$WORK/app-out" >/dev/null 2>&1
|
||||
cmp -s "$TD/mixed/text.txt" "$WORK/app-out/text.txt" &&
|
||||
cmp -s "$TD/mixed/source.c" "$WORK/app-out/source.c" &&
|
||||
ok "appended archive extracts bit-identical" || bad "appended archive extracts bit-identical"
|
||||
|
||||
# --- 4. -r 0 equivalence with lzply ------------------------------------
|
||||
# With no RS parity, the stored bytes must be exactly the lzply -e 0
|
||||
# bytes (same lzip blob, same BCH layer): only the headers differ.
|
||||
if [ -x "$LZPLY" ]; then
|
||||
"$LZPLY" -c -6 -e 0 "$TD/mixed/text.txt" "$WORK/lp.lzply" >/dev/null 2>&1
|
||||
"$LZ_RS" -c -6 -e 0 -r 0 "$TD/mixed/text.txt" "$WORK/rs0.lzrs" >/dev/null 2>&1
|
||||
LSZ=$(($(stat -c %s "$WORK/lp.lzply") - 104 - 2))
|
||||
RSZ=$(($(stat -c %s "$WORK/rs0.lzrs") - 106 - 2))
|
||||
dd if="$WORK/lp.lzply" bs=1 skip=104 count="$LSZ" of="$WORK/lp.bin" 2>/dev/null
|
||||
dd if="$WORK/rs0.lzrs" bs=1 skip=106 count="$RSZ" of="$WORK/rs.bin" 2>/dev/null
|
||||
if [ "$LSZ" = "$RSZ" ] && cmp -s "$WORK/lp.bin" "$WORK/rs.bin"; then
|
||||
ok "-r 0 stored bytes equal lzply -e 0"
|
||||
else
|
||||
bad "-r 0 stored bytes equal lzply -e 0"
|
||||
fi
|
||||
else
|
||||
echo "SKIP: lzply binary not found, -r 0 equivalence not checked"
|
||||
fi
|
||||
|
||||
# --- 5. Corruption recovery matrix -------------------------------------
|
||||
# random.bin: 1 MiB of random data, stored uncompressed, thousands of
|
||||
# RS blocks. t = 4 * R correctable symbol errors per block.
|
||||
for R in 1 2 3 4; do
|
||||
T=$((4 * R))
|
||||
"$LZ_RS" -c -r "$R" "$TD/mixed/random.bin" "$WORK/rand-r$R.lzrs" >/dev/null 2>&1
|
||||
set -- $(data_range "$WORK/rand-r$R.lzrs" 10)
|
||||
DS=$1
|
||||
DE=$2
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT" "$WORK/c.lzrs" 42 "$T" "$DS" "$DE" >/dev/null
|
||||
rm -rf "$WORK/cout"
|
||||
if "$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
"$LZ_RS" -d -y "$WORK/c.lzrs" "$WORK/cout" >/dev/null 2>&1
|
||||
cmp -s "$TD/mixed/random.bin" "$WORK/cout/random.bin" &&
|
||||
ok "-r $R: $T scattered byte errors recovered" ||
|
||||
bad "-r $R: $T scattered byte errors recovered"
|
||||
else
|
||||
bad "-r $R: $T scattered byte errors recovered"
|
||||
fi
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT" "$WORK/c.lzrs" 7 "$T" "$DS" $((DS + 255)) >/dev/null
|
||||
if "$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
ok "-r $R: $T byte errors in one block recovered"
|
||||
else
|
||||
bad "-r $R: $T byte errors in one block recovered"
|
||||
fi
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT_RUN" "$WORK/c.lzrs" "$DS" "$T" >/dev/null
|
||||
if "$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
ok "-r $R: burst of $T bytes recovered"
|
||||
else
|
||||
bad "-r $R: burst of $T bytes recovered"
|
||||
fi
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT_RUN" "$WORK/c.lzrs" $((DS + 255 - T)) $((2 * T)) >/dev/null
|
||||
if "$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
ok "-r $R: burst of $((2 * T)) bytes over a block boundary recovered"
|
||||
else
|
||||
bad "-r $R: burst of $((2 * T)) bytes over a block boundary recovered"
|
||||
fi
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT" "$WORK/c.lzrs" 11 $((T + 1)) "$DS" $((DS + 255)) >/dev/null
|
||||
"$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1
|
||||
RC=$?
|
||||
if [ "$RC" = 3 ]; then
|
||||
ok "-r $R: $((T + 1)) byte errors in one block fail (exit 3)"
|
||||
else
|
||||
bad "-r $R: $((T + 1)) byte errors in one block fail (exit 3, got $RC)"
|
||||
fi
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT_RUN" "$WORK/c.lzrs" "$DS" $((T + 1)) >/dev/null
|
||||
"$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1
|
||||
RC=$?
|
||||
if [ "$RC" = 3 ]; then
|
||||
ok "-r $R: burst of $((T + 1)) bytes fails (exit 3)"
|
||||
else
|
||||
bad "-r $R: burst of $((T + 1)) bytes fails (exit 3, got $RC)"
|
||||
fi
|
||||
|
||||
cp "$WORK/rand-r$R.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT_BITS" "$WORK/c.lzrs" 99 8 "$DS" "$DE" >/dev/null
|
||||
if "$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
ok "-r $R: 8 scattered bit errors recovered"
|
||||
else
|
||||
bad "-r $R: 8 scattered bit errors recovered"
|
||||
fi
|
||||
|
||||
if "$LZ_RS" -i "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
ok "-r $R: -i works on corrupted data"
|
||||
else
|
||||
bad "-r $R: -i works on corrupted data"
|
||||
fi
|
||||
done
|
||||
|
||||
# --- 6. RS-only matrix (-e 0): RS alone recovers t, fails at t+1 ------
|
||||
"$LZ_RS" -c -e 0 -r 2 "$TD/mixed/random.bin" "$WORK/rand-e0.lzrs" >/dev/null 2>&1
|
||||
set -- $(data_range "$WORK/rand-e0.lzrs" 10)
|
||||
DS=$1
|
||||
DE=$2
|
||||
cp "$WORK/rand-e0.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT" "$WORK/c.lzrs" 5 8 "$DS" "$DE" >/dev/null
|
||||
if "$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1; then
|
||||
ok "-e 0 -r 2: 8 scattered byte errors recovered (RS only)"
|
||||
else
|
||||
bad "-e 0 -r 2: 8 scattered byte errors recovered (RS only)"
|
||||
fi
|
||||
cp "$WORK/rand-e0.lzrs" "$WORK/c.lzrs"
|
||||
"$CORRUPT" "$WORK/c.lzrs" 6 9 "$DS" $((DS + 255)) >/dev/null
|
||||
"$LZ_RS" -t "$WORK/c.lzrs" >/dev/null 2>&1
|
||||
RC=$?
|
||||
if [ "$RC" = 3 ]; then
|
||||
ok "-e 0 -r 2: 9 byte errors in one block fail (exit 3)"
|
||||
else
|
||||
bad "-e 0 -r 2: 9 byte errors in one block fail (exit 3, got $RC)"
|
||||
fi
|
||||
|
||||
# --- 7. Format rejection and truncation --------------------------------
|
||||
"$LZ_RS" -c -r 2 "$TD/mixed/text.txt" "$WORK/x.lzrs" >/dev/null 2>&1
|
||||
if [ -x "$LZPLY" ]; then
|
||||
if "$LZPLY" -t "$WORK/x.lzrs" >/dev/null 2>&1; then
|
||||
bad "lzply rejects .lzrs archives"
|
||||
else
|
||||
ok "lzply rejects .lzrs archives"
|
||||
fi
|
||||
"$LZPLY" -c -e 0 "$TD/mixed/text.txt" "$WORK/y.lzply" >/dev/null 2>&1
|
||||
if "$LZ_RS" -t "$WORK/y.lzply" >/dev/null 2>&1; then
|
||||
bad "lz_rs rejects .lzply archives"
|
||||
else
|
||||
ok "lz_rs rejects .lzply archives"
|
||||
fi
|
||||
else
|
||||
echo "SKIP: lzply binary not found, format rejection not checked"
|
||||
fi
|
||||
|
||||
SZ=$(stat -c %s "$WORK/x.lzrs")
|
||||
dd if="$WORK/x.lzrs" bs=1 count=$((SZ - 100)) of="$WORK/trunc.lzrs" 2>/dev/null
|
||||
if "$LZ_RS" -t "$WORK/trunc.lzrs" >/dev/null 2>&1; then
|
||||
bad "truncated archive fails"
|
||||
else
|
||||
ok "truncated archive fails"
|
||||
fi
|
||||
|
||||
# CRC16 (v5 migration): -i shows a crc16 column, and an archive with
|
||||
# crc16 zeroed (pre-migration) is rejected cleanly.
|
||||
"$LZ_RS" -i "$WORK/x.lzrs" 2>/dev/null | grep -qE '[0-9a-f]{4}$' &&
|
||||
ok "-i shows a crc16 column" || bad "-i shows a crc16 column"
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
cp "$WORK/x.lzrs" "$WORK/oldcrc.lzrs"
|
||||
python3 - "$WORK/oldcrc.lzrs" << 'PYEOF'
|
||||
import binascii, struct, sys
|
||||
p = sys.argv[1]
|
||||
d = bytearray(open(p, "rb").read())
|
||||
d[16 + 76:16 + 78] = b"\x00\x00"
|
||||
struct.pack_into("<I", d, 16 + 78, binascii.crc32(bytes(d[16:16 + 78])) & 0xffffffff)
|
||||
open(p, "wb").write(bytes(d))
|
||||
PYEOF
|
||||
if "$LZ_RS" -t "$WORK/oldcrc.lzrs" 2>&1 | grep -q "predates the CRC16 migration"; then
|
||||
ok "old LZRS (crc16 zero) is rejected with the migration message"
|
||||
else
|
||||
bad "old LZRS (crc16 zero) must be rejected with the migration message"
|
||||
fi
|
||||
else
|
||||
echo "SKIP: python3 not found, old-CRC16 rejection not checked"
|
||||
fi
|
||||
|
||||
# --- 8. Benchmarks ------------------------------------------------------
|
||||
echo "--- benchmarks: testdata/mixed, 13 entries ---"
|
||||
printf "%-4s %12s %10s %10s\n" "r" "archive" "compress" "extract"
|
||||
for R in 0 1 2 3 4; do
|
||||
S=$(date +%s%N)
|
||||
"$LZ_RS" -c -r "$R" "$TD/mixed" "$WORK/bench-r$R.lzrs" >/dev/null 2>&1
|
||||
E=$(date +%s%N)
|
||||
C_MS=$(((E - S) / 1000000))
|
||||
SZ=$(stat -c %s "$WORK/bench-r$R.lzrs")
|
||||
rm -rf "$WORK/bench-out"
|
||||
S=$(date +%s%N)
|
||||
"$LZ_RS" -d -y "$WORK/bench-r$R.lzrs" "$WORK/bench-out" >/dev/null 2>&1
|
||||
E=$(date +%s%N)
|
||||
D_MS=$(((E - S) / 1000000))
|
||||
printf "%-4s %12s %10s %10s\n" "r$R" "$SZ" "${C_MS}ms" "${D_MS}ms"
|
||||
done
|
||||
|
||||
echo "run_rs_tests: $PASS passed, $FAIL failed"
|
||||
if [ "$FAIL" = 0 ]; then exit 0; else exit 1; fi
|
||||
+24
-36
@@ -55,10 +55,10 @@ done
|
||||
# (Skipped when the system lzip tool is not installed.)
|
||||
if command -v lzip >/dev/null 2>&1; then
|
||||
"$LZPLY" -c -6 -e 0 "$TD/mixed/text.txt" "$WORK/text6.lzply" >/dev/null 2>&1
|
||||
# archive layout: 16 (global) + 80 (entry header) + 8 ("text.txt") = 104,
|
||||
# archive layout: 16 (global) + 78 (entry header) + 8 ("text.txt") = 102,
|
||||
# then stored_size bytes, then the 2-byte end marker.
|
||||
ASZ=$(stat -c %s "$WORK/text6.lzply")
|
||||
dd if="$WORK/text6.lzply" bs=1 skip=104 count=$((ASZ - 106)) status=none > "$WORK/text6.lzip" 2>/dev/null
|
||||
dd if="$WORK/text6.lzply" bs=1 skip=102 count=$((ASZ - 104)) status=none > "$WORK/text6.lzip" 2>/dev/null
|
||||
lzip -6 -c "$TD/mixed/text.txt" > "$WORK/text6.ref" 2>/dev/null
|
||||
if cmp -s <(tail -c +7 "$WORK/text6.lzip") <(tail -c +7 "$WORK/text6.ref") &&
|
||||
[ "$(stat -c %s "$WORK/text6.lzip")" = "$(stat -c %s "$WORK/text6.ref")" ] &&
|
||||
@@ -83,16 +83,16 @@ for E in 0 1 2 3 4 5 6 7; do
|
||||
done
|
||||
|
||||
# --- 4. BCH corruption: single-file archive of text.txt -----------------
|
||||
# Stored data starts at offset 104 (16 + 80 + 8 for "text.txt"). All
|
||||
# Stored data starts at offset 102 (16 + 78 + 8 for "text.txt"). All
|
||||
# flipped bits must land in ONE BCH block, so the flip range is the
|
||||
# first block. For most pinned polys the blob is a single block
|
||||
# (range = whole stored region); poly 0002 (m7,t2) has max_data 14
|
||||
# bytes, so its first block is only 16 stored bytes ([104,120)).
|
||||
# bytes, so its first block is only 16 stored bytes ([102,118)).
|
||||
# Flip exactly t bits in the first block -> must recover; flip t+1
|
||||
# bits -> must fail cleanly (BCH uncorrectable, or SHA-256 catches a
|
||||
# miscorrection). Pinned polys so t is known exactly.
|
||||
# SPEC: poly t end_offset(0 = end of stored region)
|
||||
for SPEC in "0002 2 120" "0018 2 0" "0025 4 0" "003a 32 0"; do
|
||||
for SPEC in "0002 2 118" "0018 2 0" "0025 4 0" "003a 32 0"; do
|
||||
set -- $SPEC
|
||||
POLY=$1; T=$2; ENDFIX=$3
|
||||
"$LZPLY" -c -6 poly="$POLY" "$TD/mixed/text.txt" "$WORK/bch-$POLY.lzply" >/dev/null 2>&1
|
||||
@@ -100,7 +100,7 @@ for SPEC in "0002 2 120" "0018 2 0" "0025 4 0" "003a 32 0"; do
|
||||
if [ "$ENDFIX" = "0" ]; then END=$((SZ - 2)); else END=$ENDFIX; fi
|
||||
# (a) t bit errors -> must recover
|
||||
cp "$WORK/bch-$POLY.lzply" "$WORK/bch-${POLY}a.lzply"
|
||||
"$CORRUPT_BITS" "$WORK/bch-${POLY}a.lzply" 42 "$T" 104 "$END" >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/bch-${POLY}a.lzply" 42 "$T" 102 "$END" >/dev/null
|
||||
rm -rf "$WORK/out"
|
||||
if "$LZPLY" -d "$WORK/bch-${POLY}a.lzply" "$WORK/out" >/dev/null 2>&1 &&
|
||||
cmp -s "$TD/mixed/text.txt" "$WORK/out/text.txt"; then
|
||||
@@ -110,7 +110,7 @@ for SPEC in "0002 2 120" "0018 2 0" "0025 4 0" "003a 32 0"; do
|
||||
fi
|
||||
# (b) t+1 bit errors -> must fail cleanly (never silent wrong data)
|
||||
cp "$WORK/bch-$POLY.lzply" "$WORK/bch-${POLY}b.lzply"
|
||||
"$CORRUPT_BITS" "$WORK/bch-${POLY}b.lzply" 43 $((T + 1)) 104 "$END" >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/bch-${POLY}b.lzply" 43 $((T + 1)) 102 "$END" >/dev/null
|
||||
rm -rf "$WORK/out"
|
||||
if "$LZPLY" -d "$WORK/bch-${POLY}b.lzply" "$WORK/out" >/dev/null 2>&1; then
|
||||
bad "BCH poly $POLY: $((T+1)) bit errors must fail"
|
||||
@@ -124,7 +124,7 @@ done
|
||||
"$LZPLY" -c -9 -e 5 "$TD/mixed/text.txt" "$WORK/combo.lzply" >/dev/null 2>&1
|
||||
cp "$WORK/combo.lzply" "$WORK/combo-c.lzply"
|
||||
SZ=$(stat -c %s "$WORK/combo-c.lzply")
|
||||
"$CORRUPT_BITS" "$WORK/combo-c.lzply" 46 16 104 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/combo-c.lzply" 46 16 102 $((SZ - 2)) >/dev/null
|
||||
rm -rf "$WORK/out"
|
||||
"$LZPLY" -d "$WORK/combo-c.lzply" "$WORK/out" >/dev/null 2>&1 &&
|
||||
cmp -s "$TD/mixed/text.txt" "$WORK/out/text.txt" &&
|
||||
@@ -139,15 +139,6 @@ if "$LZPLY" -t "$WORK/v3patched.lzply" >/dev/null 2>&1; then
|
||||
else
|
||||
ok "v3 archive (version byte 3) is rejected (bad magic/version)"
|
||||
fi
|
||||
# v4 archive rejected: same patch to version byte 4, with the
|
||||
# migration message (v4 predates the CRC16 migration to v5)
|
||||
cp "$WORK/v3.lzply" "$WORK/v4patched.lzply"
|
||||
printf '\x04' | dd of="$WORK/v4patched.lzply" bs=1 seek=4 conv=notrunc status=none 2>/dev/null
|
||||
if "$LZPLY" -t "$WORK/v4patched.lzply" 2>&1 | grep -q "predates the CRC16 migration"; then
|
||||
ok "v4 archive (version byte 4) is rejected with the migration message"
|
||||
else
|
||||
bad "v4 archive (version byte 4) must be rejected with the migration message"
|
||||
fi
|
||||
# the removed option is now a usage error (exit 1)
|
||||
# (built by concatenation so the removed name does not appear literally)
|
||||
"$LZPLY" -c -6 -pass"word=foo" >/dev/null 2>&1
|
||||
@@ -270,20 +261,17 @@ if "$LZPLY" -c -6 poly=00ff "$TD/mixed/text.txt" "$WORK/badpoly3.lzply" >/dev/nu
|
||||
else
|
||||
ok "poly=00ff rejected (usage error)"
|
||||
fi
|
||||
# format version byte (offset 4): 5 for the v5 format, with or
|
||||
# format version byte (offset 4): 4 for the v4 format, with or
|
||||
# without BCH (a single format now; no legacy versions).
|
||||
V_BCH=$(od -An -tu1 -j 4 -N 1 "$WORK/mixed-e4.lzply" | tr -d ' ')
|
||||
V_NOECC=$(od -An -tu1 -j 4 -N 1 "$WORK/mixed-e0.lzply" | tr -d ' ')
|
||||
[ "$V_BCH" = "5" ] && ok "BCH archive has version byte 5" || bad "BCH archive has version byte 5 (got $V_BCH)"
|
||||
[ "$V_NOECC" = "5" ] && ok "no-ECC archive has version byte 5" || bad "no-ECC archive has version byte 5 (got $V_NOECC)"
|
||||
# -i shows the crc16 column for every entry (v5)
|
||||
"$LZPLY" -i "$WORK/mixed-e4.lzply" 2>/dev/null | grep -qE '[0-9a-f]{4}$' &&
|
||||
ok "-i shows a crc16 column" || bad "-i shows a crc16 column"
|
||||
[ "$V_BCH" = "4" ] && ok "BCH archive has version byte 4" || bad "BCH archive has version byte 4 (got $V_BCH)"
|
||||
[ "$V_NOECC" = "4" ] && ok "no-ECC archive has version byte 4" || bad "no-ECC archive has version byte 4 (got $V_NOECC)"
|
||||
|
||||
# --- 11. Block splitting: blob > one block, with corruption -----------
|
||||
# 600 KiB random file: blob ~600 KiB > max single block for the
|
||||
# auto-picked poly, so it splits. Corrupt bits in the first block
|
||||
# (offset 105, well inside block 1) and verify recovery / failure.
|
||||
# (offset 102, well inside block 1) and verify recovery / failure.
|
||||
head -c 614400 /dev/urandom > "$WORK/split.bin"
|
||||
"$LZPLY" -c -6 "$WORK/split.bin" "$WORK/split.lzply" >/dev/null 2>&1
|
||||
rm -rf "$WORK/out"
|
||||
@@ -291,14 +279,14 @@ rm -rf "$WORK/out"
|
||||
cmp -s "$WORK/split.bin" "$WORK/out/split.bin" &&
|
||||
ok "600 KiB split-blob roundtrip" || bad "600 KiB split-blob roundtrip"
|
||||
cp "$WORK/split.lzply" "$WORK/split-a.lzply"
|
||||
"$CORRUPT_BITS" "$WORK/split-a.lzply" 51 8 105 1105 >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/split-a.lzply" 51 8 102 1102 >/dev/null
|
||||
rm -rf "$WORK/out"
|
||||
"$LZPLY" -d "$WORK/split-a.lzply" "$WORK/out" >/dev/null 2>&1 &&
|
||||
cmp -s "$WORK/split.bin" "$WORK/out/split.bin" &&
|
||||
ok "split-blob: 8 bit errors in first block recovered" ||
|
||||
bad "split-blob: 8 bit errors in first block recovered"
|
||||
cp "$WORK/split.lzply" "$WORK/split-b.lzply"
|
||||
"$CORRUPT_BITS" "$WORK/split-b.lzply" 52 9 105 1105 >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/split-b.lzply" 52 9 102 1102 >/dev/null
|
||||
rm -rf "$WORK/out"
|
||||
if "$LZPLY" -d "$WORK/split-b.lzply" "$WORK/out" >/dev/null 2>&1; then
|
||||
bad "split-blob: 9 bit errors in first block must fail"
|
||||
@@ -497,13 +485,13 @@ echo "$OUT" | grep -q "5 entries (3 directories, 2 files)" &&
|
||||
ok "-i: summary counts 5 entries (3 dirs, 2 files)" ||
|
||||
bad "-i: summary counts 5 entries (3 dirs, 2 files)"
|
||||
# -i reads headers only: corrupt the data of a single-file archive
|
||||
# (data starts at 104 for an 8-char path) and -i still succeeds while
|
||||
# (data starts at 102 for an 8-char path) and -i still succeeds while
|
||||
# -t fails. The file is 1 KiB of random data, so the stored blob is
|
||||
# ~1 KiB and 100 zeroed bytes at 104 are well inside it.
|
||||
# ~1 KiB and 100 zeroed bytes at 102 are well inside it.
|
||||
head -c 1024 /dev/urandom > "$WORK/rand.bin"
|
||||
"$LZPLY" -c -y -6 "$WORK/rand.bin" "$WORK/rand.lzply" >/dev/null 2>&1
|
||||
cp "$WORK/rand.lzply" "$WORK/rand-corrupt.lzply"
|
||||
dd if=/dev/zero of="$WORK/rand-corrupt.lzply" bs=1 seek=104 count=100 conv=notrunc status=none
|
||||
dd if=/dev/zero of="$WORK/rand-corrupt.lzply" bs=1 seek=102 count=100 conv=notrunc status=none
|
||||
"$LZPLY" -i "$WORK/rand-corrupt.lzply" >/dev/null 2>&1 &&
|
||||
ok "-i succeeds on an archive whose data is corrupted (headers only)" ||
|
||||
bad "-i succeeds on an archive whose data is corrupted (headers only)"
|
||||
@@ -750,14 +738,14 @@ cp "$WORK/stat.lzply" "$WORK/heal-strip.lzply"
|
||||
ok "lzply_heal -e 0: ECC stripped, archive still verifies" ||
|
||||
bad "lzply_heal -e 0: ECC stripped, archive still verifies"
|
||||
# (d) bit-error correction: single-file archive, -e 4 (t=8), one block.
|
||||
# Data starts at 104 (16 + 80 + 8 for "tiny.txt"); flip 5 bits in the
|
||||
# Data starts at 102 (16 + 78 + 8 for "tiny.txt"); flip 5 bits in the
|
||||
# stored region -> heal recovers; flip 9 -> uncorrectable (exit non-zero,
|
||||
# entry kept, -t still fails).
|
||||
printf 'heal bit test\n' > "$WORK/tiny.txt"
|
||||
"$LZPLY" -c -y -6 -e 4 "$WORK/tiny.txt" "$WORK/heal-bits.lzply" >/dev/null 2>&1
|
||||
cp "$WORK/heal-bits.lzply" "$WORK/heal-bits-a.lzply"
|
||||
SZ=$(stat -c %s "$WORK/heal-bits-a.lzply")
|
||||
"$CORRUPT_BITS" "$WORK/heal-bits-a.lzply" 61 5 104 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/heal-bits-a.lzply" 61 5 102 $((SZ - 2)) >/dev/null
|
||||
"$HEAL" "$WORK/heal-bits-a.lzply" >/dev/null 2>&1 &&
|
||||
"$LZPLY" -t "$WORK/heal-bits-a.lzply" >/dev/null 2>&1 &&
|
||||
rm -rf "$WORK/out" &&
|
||||
@@ -767,7 +755,7 @@ cmp -s "$WORK/tiny.txt" "$WORK/out/tiny.txt" &&
|
||||
bad "lzply_heal: 5 flipped bits (t=8) corrected, data recovered"
|
||||
cp "$WORK/heal-bits.lzply" "$WORK/heal-bits-b.lzply"
|
||||
SZ=$(stat -c %s "$WORK/heal-bits-b.lzply")
|
||||
"$CORRUPT_BITS" "$WORK/heal-bits-b.lzply" 62 9 104 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/heal-bits-b.lzply" 62 9 102 $((SZ - 2)) >/dev/null
|
||||
if "$HEAL" "$WORK/heal-bits-b.lzply" >/dev/null 2>&1; then
|
||||
bad "lzply_heal: 9 flipped bits (t=8) must exit non-zero"
|
||||
else
|
||||
@@ -814,7 +802,7 @@ echo "$OUT" | grep "tiny.txt" | grep -q "clean" &&
|
||||
# BER == 5 / (8 * stored_size), verified through --json.
|
||||
cp "$WORK/check-clean.lzply" "$WORK/check-err5.lzply"
|
||||
SZ=$(stat -c %s "$WORK/check-err5.lzply")
|
||||
"$CORRUPT_BITS" "$WORK/check-err5.lzply" 61 5 104 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/check-err5.lzply" 61 5 102 $((SZ - 2)) >/dev/null
|
||||
"$CHECK" --json "$WORK/check-err5.lzply" 2>/dev/null | python3 -c '
|
||||
import json, sys
|
||||
d = json.load(sys.stdin)
|
||||
@@ -831,7 +819,7 @@ print("json ok")
|
||||
# (c) uncorrectable: 9 bits flipped (t=8) -> exit 3, uncorrectable
|
||||
cp "$WORK/check-clean.lzply" "$WORK/check-err9.lzply"
|
||||
SZ=$(stat -c %s "$WORK/check-err9.lzply")
|
||||
"$CORRUPT_BITS" "$WORK/check-err9.lzply" 62 9 104 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/check-err9.lzply" 62 9 102 $((SZ - 2)) >/dev/null
|
||||
OUT=$("$CHECK" "$WORK/check-err9.lzply" 2>&1)
|
||||
RC=$?
|
||||
[ "$RC" = "3" ] && echo "$OUT" | grep -q "uncorrectable" &&
|
||||
@@ -1092,12 +1080,12 @@ cmp -s "$TD/mixed/text.txt" "$WORK/out/text.txt" &&
|
||||
ok "store mode: -0 archive extracts byte-identical" ||
|
||||
bad "store mode: -0 archive extracts byte-identical"
|
||||
# (4) BCH still applies to stored entries: flip 1 bit in the stored
|
||||
# entry (data starts at 106: 16 + 80 + 10 for "random.bin"); -t still
|
||||
# entry (data starts at 104: 16 + 78 + 10 for "random.bin"); -t still
|
||||
# passes (BCH corrects it), check reports exactly 1 corrected bit,
|
||||
# heal fixes it and the healed archive extracts byte-identical.
|
||||
cp "$WORK/store-rand.lzply" "$WORK/store-rand-c.lzply"
|
||||
SZ=$(stat -c %s "$WORK/store-rand-c.lzply")
|
||||
"$CORRUPT_BITS" "$WORK/store-rand-c.lzply" 55 1 106 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/store-rand-c.lzply" 55 1 104 $((SZ - 2)) >/dev/null
|
||||
"$LZPLY" -t "$WORK/store-rand-c.lzply" >/dev/null 2>&1 &&
|
||||
ok "store mode: 1 flipped bit in a stored entry still tests OK (BCH)" ||
|
||||
bad "store mode: 1 flipped bit in a stored entry still tests OK (BCH)"
|
||||
|
||||
Reference in new issue
Block a user