Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a34cd7dcaf | ||
|
|
3dce1f4e59 | ||
|
|
f87c7e3007 | ||
|
|
f07a2ba488 | ||
|
|
4b6d4cfa45 | ||
|
|
5d3ee79fd3 | ||
|
|
22436a7990 | ||
|
|
5d4f17a57e | ||
|
|
50b3b3a80f | ||
|
|
1f959bb211 |
No files matched your search
-13
@@ -14,16 +14,3 @@
|
||||
/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)
|
||||
/experiments/corpora/
|
||||
/experiments/rans_tool
|
||||
/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 +1,7 @@
|
||||
bench
|
||||
ldpc_diag
|
||||
pass2_diag
|
||||
uep_diag
|
||||
*.o
|
||||
corpora/
|
||||
results/
|
||||
+5
-2
@@ -4,7 +4,7 @@ CC ?= gcc
|
||||
CFLAGS ?= -O2 -Wall -Wextra -march=native
|
||||
CPPFLAGS ?= -I. -I..
|
||||
|
||||
SRCS = bench.c bch_wrap.c interleave.c ldpc.c \
|
||||
SRCS = bench.c bch_wrap.c interleave.c ldpc.c polar.c uep.c \
|
||||
../bch.c ../sha256.c
|
||||
OBJS = $(SRCS:.c=.o)
|
||||
|
||||
@@ -17,10 +17,13 @@ ldpc_diag: ldpc_diag.c ldpc.c
|
||||
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
|
||||
|
||||
uep_diag: uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c -lm
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f bench ldpc_diag pass2_diag $(OBJS)
|
||||
rm -f bench ldpc_diag pass2_diag uep_diag $(OBJS)
|
||||
|
||||
.PHONY: clean
|
||||
@@ -1,10 +1,5 @@
|
||||
# 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
|
||||
|
||||
+12
-1
@@ -37,6 +37,8 @@ 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);
|
||||
ecc_codec_t *polar_new(int rate_pct, int design_exp);
|
||||
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
|
||||
|
||||
static ecc_codec_t *make_codec(const char *name)
|
||||
{
|
||||
@@ -50,6 +52,14 @@ static ecc_codec_t *make_codec(const char *name)
|
||||
return interleave_new(d, t);
|
||||
if (sscanf(name, "ldpc-r%d", &v) == 1)
|
||||
return ldpc_new(v);
|
||||
int dexp;
|
||||
if (sscanf(name, "polar-r%d-d%d", &v, &dexp) == 2)
|
||||
return polar_new(v, dexp);
|
||||
if (sscanf(name, "polar-r%d", &v) == 1)
|
||||
return polar_new(v, 2);
|
||||
int cb, th, tl;
|
||||
if (sscanf(name, "uep-c%d-h%d-l%d", &cb, &th, &tl) == 3)
|
||||
return uep_new(cb, th, tl);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -104,7 +114,8 @@ static void usage(void)
|
||||
" [--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");
|
||||
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n"
|
||||
" polar-r{90,95} uep-c{1024,4096}-h{16,32}-l{2,4}\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
/* polar.c - polar code codec for the experiments harness.
|
||||
*
|
||||
* N=4096, successive-cancellation (SC) decoding with the min-sum
|
||||
* f-function. Construction is Arikan's Bhattacharyya recursion for
|
||||
* the binary erasure channel with erasure probability equal to the
|
||||
* BSC's Bhattacharyya parameter Z = 2*sqrt(p(1-p)) at a design
|
||||
* crossover p (see polar_new: the codec name selects it, e.g.
|
||||
* polar-r90-d3 designs for p=1e-3; plain polar-r90 designs for
|
||||
* p=1e-2). The design point matters: designing for a much worse
|
||||
* channel than the operating point ranks the marginal channels
|
||||
* wrong and SC pays for it.
|
||||
*
|
||||
* polar-r90: K=3680 info bits (460 B), rate 0.89844, overhead 11.30%.
|
||||
* polar-r95: K=3888 info bits (486 B), rate 0.94922, overhead 5.35%.
|
||||
*
|
||||
* A blob is split into blocks of K data bytes; the last block is
|
||||
* zero-padded. Stored length per block is exactly N/8 = 512 bytes.
|
||||
*
|
||||
* Note: SC decoding always returns a codeword, so decode() cannot
|
||||
* detect failure by itself -- it returns 0 whenever decoding
|
||||
* completes, and the caller (bench / lzply's SHA-256) is the oracle
|
||||
* that decides whether the recovered data is correct. That matches
|
||||
* lzply's architecture: the entry SHA is the miscorrection guard.
|
||||
* Channel LLR uses a fixed nominal crossover p0 = 1e-3, same honest
|
||||
* setting as the LDPC codec.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
#define POLAR_N 4096
|
||||
#define POLAR_LOGN 12
|
||||
#define POLAR_P0 1e-3
|
||||
|
||||
typedef struct {
|
||||
int k; /* info bits */
|
||||
int kbytes; /* info bytes per block */
|
||||
double p_design; /* design crossover for the BEC construction */
|
||||
uint8_t frozen[POLAR_N]; /* 1 = frozen (0 bit) */
|
||||
float *llr; /* N, decode workspace */
|
||||
float *ws; /* N, SC scratch (bump-allocated down the tree) */
|
||||
uint8_t *bits; /* N, decoded info vector (leaf decisions) */
|
||||
uint8_t *psum; /* N, partial sums (re-encoded codeword) */
|
||||
} polar_t;
|
||||
|
||||
static void polar_build_frozen(polar_t *P)
|
||||
{
|
||||
/* BEC Bhattacharyya recursion: Z starts at eps, then per level
|
||||
the upper (bad) channel gets 2Z-Z^2 and the lower (good) one
|
||||
gets Z^2. z[] holds the values in bit-reversed order matching
|
||||
the standard construction; sorting by Z ascending gives the
|
||||
reliability order. */
|
||||
double eps = 2.0 * sqrt(P->p_design * (1.0 - P->p_design));
|
||||
double z[POLAR_N];
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
z[i] = eps;
|
||||
for (int level = 0; level < POLAR_LOGN; level++) {
|
||||
int step = 1 << (level + 1);
|
||||
int half = 1 << level;
|
||||
for (int base = 0; base < POLAR_N; base += step) {
|
||||
for (int i = 0; i < half; i++) {
|
||||
double a = z[base + i];
|
||||
double b = z[base + half + i];
|
||||
/* upper (first half) is the worse channel */
|
||||
z[base + i] = 2 * a - a * a;
|
||||
z[base + half + i] = b * b;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The recursion above indexes channels in natural order only if
|
||||
the pairing is right; verify by construction: sort indices by
|
||||
Z and take the K smallest as information positions. */
|
||||
int idx[POLAR_N];
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
idx[i] = i;
|
||||
/* simple insertion-free sort: qsort with a comparator on z */
|
||||
/* (z is captured via a file-scope pointer for the comparator) */
|
||||
extern double *polar_sort_z;
|
||||
polar_sort_z = z;
|
||||
/* qsort needs a comparator; defined below */
|
||||
extern int polar_cmp_idx(const void *, const void *);
|
||||
qsort(idx, POLAR_N, sizeof(int), polar_cmp_idx);
|
||||
memset(P->frozen, 1, POLAR_N);
|
||||
for (int i = 0; i < P->k; i++)
|
||||
P->frozen[idx[i]] = 0;
|
||||
}
|
||||
|
||||
double *polar_sort_z = NULL;
|
||||
int polar_cmp_idx(const void *a, const void *b)
|
||||
{
|
||||
int ia = *(const int *)a, ib = *(const int *)b;
|
||||
if (polar_sort_z[ia] < polar_sort_z[ib])
|
||||
return -1;
|
||||
if (polar_sort_z[ia] > polar_sort_z[ib])
|
||||
return 1;
|
||||
return ia - ib;
|
||||
}
|
||||
|
||||
/* polar transform: in-place butterfly, u ^= u shifted */
|
||||
static void polar_transform(uint8_t *u, int n)
|
||||
{
|
||||
for (int len = 1; len < n; len <<= 1) {
|
||||
for (int base = 0; base < n; base += 2 * len) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
int a = base + i, b = base + len + i;
|
||||
u[a] ^= u[b];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 polar_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
polar_t *P = (polar_t *)c->priv;
|
||||
size_t nblocks = (len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
|
||||
size_t slen = nblocks * (POLAR_N / 8);
|
||||
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
|
||||
if (!buf)
|
||||
return 0;
|
||||
uint8_t *u = (uint8_t *)malloc(POLAR_N);
|
||||
if (!u) {
|
||||
free(buf);
|
||||
return 0;
|
||||
}
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
size_t dlen = len - b * (size_t)P->kbytes < (size_t)P->kbytes
|
||||
? len - b * (size_t)P->kbytes
|
||||
: (size_t)P->kbytes;
|
||||
memset(u, 0, POLAR_N);
|
||||
int dp = 0;
|
||||
for (int i = 0; i < POLAR_N; i++) {
|
||||
if (P->frozen[i])
|
||||
continue;
|
||||
if (dp < (int)dlen * 8)
|
||||
u[i] = (uint8_t)get_bit(data + b * (size_t)P->kbytes, dp);
|
||||
dp++;
|
||||
}
|
||||
polar_transform(u, POLAR_N);
|
||||
uint8_t *cw = buf + b * (POLAR_N / 8);
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
set_bit(cw, i, u[i]);
|
||||
}
|
||||
free(u);
|
||||
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static inline float polar_f(float a, float b)
|
||||
{
|
||||
float m = fabsf(a) < fabsf(b) ? fabsf(a) : fabsf(b);
|
||||
int s = ((a < 0) ^ (b < 0)) ? -1 : 1;
|
||||
return s * m;
|
||||
}
|
||||
static inline float polar_g(float a, float b, int u)
|
||||
{
|
||||
return b + (u ? -a : a);
|
||||
}
|
||||
|
||||
static void sc_rec(polar_t *P, const float *llr, int off, int len,
|
||||
float *ws)
|
||||
{
|
||||
if (len == 1) {
|
||||
/* Leaf: the decision is the decoded info bit. The partial
|
||||
sum at a leaf is the bit itself. The two arrays must stay
|
||||
separate: the combine step below rewrites psum (it becomes
|
||||
the re-encoded codeword) and must not touch bits. */
|
||||
int b = 0;
|
||||
if (!P->frozen[off])
|
||||
b = llr[0] < 0 ? 1 : 0;
|
||||
P->bits[off] = (uint8_t)b;
|
||||
P->psum[off] = (uint8_t)b;
|
||||
return;
|
||||
}
|
||||
int half = len / 2;
|
||||
/* Scratch for this level lives in ws[0..half); children bump
|
||||
past it. Total scratch along any path is N floats. */
|
||||
float *tmp = ws;
|
||||
for (int i = 0; i < half; i++)
|
||||
tmp[i] = polar_f(llr[i], llr[half + i]);
|
||||
sc_rec(P, tmp, off, half, ws + half);
|
||||
for (int i = 0; i < half; i++)
|
||||
tmp[i] = polar_g(llr[i], llr[half + i], P->psum[off + i]);
|
||||
sc_rec(P, tmp, off + half, half, ws + half);
|
||||
for (int i = 0; i < half; i++)
|
||||
P->psum[off + i] ^= P->psum[off + half + i];
|
||||
}
|
||||
|
||||
static int polar_decode_block(polar_t *P, const uint8_t *cw_in,
|
||||
uint8_t *data_out, long *corrected_out)
|
||||
{
|
||||
float L0 = (float)log((1.0 - POLAR_P0) / POLAR_P0);
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
P->llr[i] = get_bit(cw_in, i) ? -L0 : L0;
|
||||
sc_rec(P, P->llr, 0, POLAR_N, P->ws);
|
||||
/* psum now holds the decoded codeword; count corrected bits
|
||||
against the received codeword. */
|
||||
long corr = 0;
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
if (P->psum[i] != get_bit(cw_in, i))
|
||||
corr++;
|
||||
if (corrected_out)
|
||||
*corrected_out = corr;
|
||||
/* data bits out: info positions in increasing index order */
|
||||
int dp = 0;
|
||||
memset(data_out, 0, (size_t)P->kbytes);
|
||||
for (int i = 0; i < POLAR_N; i++) {
|
||||
if (P->frozen[i])
|
||||
continue;
|
||||
set_bit(data_out, dp++, P->bits[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int polar_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
polar_t *P = (polar_t *)c->priv;
|
||||
size_t nblocks = (orig_len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
|
||||
if (slen != nblocks * (POLAR_N / 8))
|
||||
return -1;
|
||||
long corr = 0;
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
uint8_t *db = (uint8_t *)malloc((size_t)P->kbytes);
|
||||
if (!db)
|
||||
return -1;
|
||||
long bc = 0;
|
||||
polar_decode_block(P, stored + b * (POLAR_N / 8), db, &bc);
|
||||
corr += bc;
|
||||
size_t dlen = orig_len - b * (size_t)P->kbytes < (size_t)P->kbytes
|
||||
? orig_len - b * (size_t)P->kbytes
|
||||
: (size_t)P->kbytes;
|
||||
memcpy(out + b * (size_t)P->kbytes, db, dlen);
|
||||
free(db);
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = corr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void polar_destroy(ecc_codec_t *c)
|
||||
{
|
||||
polar_t *P = (polar_t *)c->priv;
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *polar_new(int rate_pct, int design_exp)
|
||||
{
|
||||
int k;
|
||||
const char *tag;
|
||||
if (rate_pct == 90) {
|
||||
k = 3680;
|
||||
tag = "polar-r90";
|
||||
} else if (rate_pct == 95) {
|
||||
k = 3888;
|
||||
tag = "polar-r95";
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
polar_t *P = (polar_t *)calloc(1, sizeof(*P));
|
||||
if (!P)
|
||||
return NULL;
|
||||
P->k = k;
|
||||
P->kbytes = k / 8;
|
||||
P->p_design = pow(10.0, -(double)design_exp);
|
||||
P->llr = (float *)malloc((size_t)POLAR_N * sizeof(float));
|
||||
P->ws = (float *)malloc((size_t)POLAR_N * sizeof(float));
|
||||
P->bits = (uint8_t *)malloc((size_t)POLAR_N);
|
||||
P->psum = (uint8_t *)malloc((size_t)POLAR_N);
|
||||
if (!P->llr || !P->ws || !P->bits || !P->psum) {
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
return NULL;
|
||||
}
|
||||
polar_build_frozen(P);
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
if (!c) {
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(24);
|
||||
if (!name) {
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
free(c);
|
||||
return NULL;
|
||||
}
|
||||
if (design_exp == 2)
|
||||
snprintf(name, 24, "%s", tag);
|
||||
else
|
||||
snprintf(name, 24, "%s-d%d", tag, design_exp);
|
||||
c->name = name;
|
||||
c->desc = "polar code, successive-cancellation decoding";
|
||||
c->block_data = (size_t)P->kbytes;
|
||||
c->encode = polar_encode;
|
||||
c->decode = polar_decode;
|
||||
c->recover_verified = NULL;
|
||||
c->destroy = polar_destroy;
|
||||
c->priv = P;
|
||||
return c;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/* uep.c - unequal error protection over small-block BCH.
|
||||
*
|
||||
* The blob is split into a critical prefix (the first C bytes -- the
|
||||
* lzip header and the start of the LZMA stream, where an error costs
|
||||
* the most) protected at BCH t_hi, and the remainder at t_lo, both
|
||||
* with m=13 small blocks. Stored = prefix_stored + rest_stored; the
|
||||
* split point is recomputed from C and orig_len, so no per-entry
|
||||
* metadata is needed beyond the codec parameters.
|
||||
*
|
||||
* Two things to know before judging it:
|
||||
* - Exact recovery is dominated by the WEAK tier: UEP cannot beat
|
||||
* uniform BCH at the same total overhead on whole-blob recovery,
|
||||
* because the weak tier fails first. The fair comparison is
|
||||
* t_lo == the uniform baseline t, with t_hi > t_lo costing only
|
||||
* a little extra overhead (the prefix is short).
|
||||
* - The win, if any, is graceful degradation: the prefix survives
|
||||
* when the rest does not. That only helps lzply if it gains a
|
||||
* salvage mode (today the entry SHA gates all-or-nothing
|
||||
* extraction), so prefix survival is reported separately by
|
||||
* uep_diag.c, not by bench.c.
|
||||
* Pass 2 is not wired: the recovery oracle is the whole-blob SHA,
|
||||
* which cannot verify a prefix candidate on its own.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "bch_wrap.h"
|
||||
#include "uep.h"
|
||||
|
||||
typedef struct {
|
||||
ecc_codec_t *hi; /* bch1k-t{t_hi} */
|
||||
ecc_codec_t *lo; /* bch1k-t{t_lo} */
|
||||
int crit_bytes;
|
||||
int t_hi, t_lo;
|
||||
} uep_priv_t;
|
||||
|
||||
/* Max data bytes per block under small-block BCH at t (pinned m=13
|
||||
poly, N=8191): floor((8191 - 13*t)/8). NOTE: this depends on t --
|
||||
971 for t=32 but 1010 for t=8. An earlier version hardcoded 971
|
||||
and broke every tier but t=32. */
|
||||
static size_t bch1k_max_data(int t)
|
||||
{
|
||||
return (8191 - (size_t)13 * (size_t)t) / 8;
|
||||
}
|
||||
|
||||
/* Stored length of dlen data bytes under small-block BCH at t:
|
||||
blocks of bch1k_max_data(t) bytes, ceil((8*dlen + t*13)/8) stored
|
||||
each. (Mirrors bch_block_stored_len for the pinned m=13 poly.) */
|
||||
static size_t bch1k_stored_len(size_t dlen, int t)
|
||||
{
|
||||
size_t maxd = bch1k_max_data(t);
|
||||
size_t total = 0;
|
||||
size_t r = (size_t)t * 13;
|
||||
while (dlen > 0) {
|
||||
size_t b = dlen < maxd ? dlen : maxd;
|
||||
total += (8 * b + r + 7) / 8;
|
||||
dlen -= b;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
static size_t uep_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
uep_priv_t *p = (uep_priv_t *)c->priv;
|
||||
size_t clen = len < (size_t)p->crit_bytes ? len : (size_t)p->crit_bytes;
|
||||
uint8_t *hi = NULL, *lo = NULL;
|
||||
size_t hi_len = p->hi->encode(p->hi, data, clen, &hi);
|
||||
size_t lo_len = 0;
|
||||
if (hi_len)
|
||||
lo_len = p->lo->encode(p->lo, data + clen, len - clen, &lo);
|
||||
if (!hi_len || (len > clen && !lo_len)) {
|
||||
free(hi);
|
||||
free(lo);
|
||||
return 0;
|
||||
}
|
||||
uint8_t *buf = (uint8_t *)malloc(hi_len + lo_len);
|
||||
if (!buf) {
|
||||
free(hi);
|
||||
free(lo);
|
||||
return 0;
|
||||
}
|
||||
memcpy(buf, hi, hi_len);
|
||||
memcpy(buf + hi_len, lo, lo_len);
|
||||
free(hi);
|
||||
free(lo);
|
||||
c->overhead = len ? (double)(hi_len + lo_len) / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return hi_len + lo_len;
|
||||
}
|
||||
|
||||
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out)
|
||||
{
|
||||
uep_priv_t *p = (uep_priv_t *)c->priv;
|
||||
size_t clen = orig_len < (size_t)p->crit_bytes
|
||||
? orig_len
|
||||
: (size_t)p->crit_bytes;
|
||||
size_t hi_len = bch1k_stored_len(clen, p->t_hi);
|
||||
size_t lo_len = bch1k_stored_len(orig_len - clen, p->t_lo);
|
||||
if (hi_len + lo_len != slen)
|
||||
return 0;
|
||||
int mask = 0;
|
||||
long corr = -1;
|
||||
if (p->hi->decode(p->hi, stored, hi_len, clen, out, &corr) == 0)
|
||||
mask |= 1;
|
||||
if (p->lo->decode(p->lo, stored + hi_len, lo_len, orig_len - clen,
|
||||
out + clen, &corr) == 0)
|
||||
mask |= 2;
|
||||
return mask;
|
||||
}
|
||||
|
||||
static int uep_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
(void)corrected;
|
||||
return uep_decode_parts(c, stored, slen, orig_len, out) == 3 ? 0 : -1;
|
||||
}
|
||||
|
||||
static void uep_destroy(ecc_codec_t *c)
|
||||
{
|
||||
uep_priv_t *p = (uep_priv_t *)c->priv;
|
||||
if (p->hi)
|
||||
p->hi->destroy(p->hi);
|
||||
if (p->lo)
|
||||
p->lo->destroy(p->lo);
|
||||
free(p);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo)
|
||||
{
|
||||
ecc_codec_t *hi = bch_1k_new(t_hi);
|
||||
ecc_codec_t *lo = bch_1k_new(t_lo);
|
||||
if (!hi || !lo) {
|
||||
if (hi)
|
||||
hi->destroy(hi);
|
||||
if (lo)
|
||||
lo->destroy(lo);
|
||||
return NULL;
|
||||
}
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
uep_priv_t *p = (uep_priv_t *)calloc(1, sizeof(*p));
|
||||
if (!c || !p) {
|
||||
free(c);
|
||||
free(p);
|
||||
hi->destroy(hi);
|
||||
lo->destroy(lo);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name) {
|
||||
free(c);
|
||||
free(p);
|
||||
hi->destroy(hi);
|
||||
lo->destroy(lo);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(name, 32, "uep-c%d-h%d-l%d", crit_bytes, t_hi, t_lo);
|
||||
p->hi = hi;
|
||||
p->lo = lo;
|
||||
p->crit_bytes = crit_bytes;
|
||||
p->t_hi = t_hi;
|
||||
p->t_lo = t_lo;
|
||||
c->name = name;
|
||||
c->desc = "unequal error protection over small-block BCH";
|
||||
c->block_data = bch1k_max_data(t_lo); /* bulk tier's block size */
|
||||
c->encode = uep_encode;
|
||||
c->decode = uep_decode;
|
||||
c->recover_verified = NULL;
|
||||
c->destroy = uep_destroy;
|
||||
c->priv = p;
|
||||
return c;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/* uep.h - UEP codec plus the part-wise decode helper used by uep_diag. */
|
||||
#ifndef EXP_UEP_H
|
||||
#define EXP_UEP_H
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
|
||||
|
||||
/* Decode and report per-part success: bit 1 = critical prefix decoded,
|
||||
bit 2 = remainder decoded. Returns the bitmask (0..3). */
|
||||
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out);
|
||||
|
||||
#endif /* EXP_UEP_H */
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
/* uep_diag.c - diagnostic for the UEP codec (NOT part of bench).
|
||||
* Reports BOTH whole-blob exact recovery AND critical-prefix survival
|
||||
* per corruption setting, so the graceful-degradation claim can be
|
||||
* judged: a prefix that survives while the rest fails is only useful
|
||||
* with a salvage mode, but it is the metric UEP exists for.
|
||||
* Usage: uep_diag <codec> <blob> <size> <trials> (--ber X | --burst L,C)
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "ecc_iface.h"
|
||||
#include "uep.h"
|
||||
|
||||
static uint64_t rs = 0x13579bdf2468aceULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc < 6) {
|
||||
fprintf(stderr,
|
||||
"usage: uep_diag <codec> <blob> <size> <trials> "
|
||||
"(--ber X | --burst L,C)\n");
|
||||
return 2;
|
||||
}
|
||||
const char *codec_name = argv[1];
|
||||
const char *blob_path = argv[2];
|
||||
size_t win_size = (size_t)strtoull(argv[3], NULL, 0);
|
||||
long trials = strtol(argv[4], NULL, 0);
|
||||
double ber = 0;
|
||||
long burst_len = 0, burst_count = 0;
|
||||
int is_burst = 0;
|
||||
if (!strcmp(argv[5], "--ber") && argc > 6)
|
||||
ber = strtod(argv[6], NULL);
|
||||
else if (!strcmp(argv[5], "--burst") && argc > 6) {
|
||||
is_burst = 1;
|
||||
burst_len = strtol(argv[6], NULL, 0);
|
||||
char *comma = strchr(argv[6], ',');
|
||||
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
|
||||
} else {
|
||||
fprintf(stderr, "uep_diag: need --ber X or --burst L,C\n");
|
||||
return 2;
|
||||
}
|
||||
FILE *f = fopen(blob_path, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "uep_diag: cannot open %s\n", blob_path);
|
||||
return 2;
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
long file_len = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
uint8_t *file = (uint8_t *)malloc((size_t)file_len);
|
||||
if (!file || fread(file, 1, (size_t)file_len, f) != (size_t)file_len)
|
||||
return 2;
|
||||
fclose(f);
|
||||
|
||||
ecc_codec_t *c = NULL;
|
||||
/* parse the codec name the same way bench does */
|
||||
int cb, th, tl;
|
||||
if (sscanf(codec_name, "uep-c%d-h%d-l%d", &cb, &th, &tl) != 3) {
|
||||
fprintf(stderr, "uep_diag: bad codec %s\n", codec_name);
|
||||
return 2;
|
||||
}
|
||||
c = uep_new(cb, th, tl);
|
||||
if (!c) {
|
||||
fprintf(stderr, "uep_diag: uep_new failed\n");
|
||||
return 2;
|
||||
}
|
||||
uint8_t *win = (uint8_t *)malloc(win_size);
|
||||
uint8_t *out = (uint8_t *)malloc(win_size);
|
||||
uint8_t *stored = NULL, *rx = NULL;
|
||||
long whole = 0, prefix = 0;
|
||||
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
|
||||
for (long tr = 0; tr < trials; tr++) {
|
||||
size_t off = (size_t)(xr() % ((size_t)file_len - win_size + 1));
|
||||
memcpy(win, file + off, win_size);
|
||||
size_t slen = c->encode(c, win, win_size, &stored);
|
||||
if (!slen) {
|
||||
fprintf(stderr, "uep_diag: encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
if (tr == 0) {
|
||||
rx = (uint8_t *)malloc(slen);
|
||||
if (!rx)
|
||||
return 2;
|
||||
}
|
||||
memcpy(rx, stored, slen);
|
||||
if (is_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);
|
||||
}
|
||||
} else {
|
||||
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;
|
||||
}
|
||||
}
|
||||
int mask = uep_decode_parts(c, rx, slen, win_size, out);
|
||||
if (mask == 3 && memcmp(out, win, win_size) == 0)
|
||||
whole++;
|
||||
if (mask & 1)
|
||||
prefix++;
|
||||
free(stored);
|
||||
stored = NULL;
|
||||
}
|
||||
printf("%s %s trials=%ld whole=%.4f prefix=%.4f overhead=%.2f%%\n",
|
||||
codec_name, is_burst ? "burst" : "ber", trials,
|
||||
(double)whole / (double)trials, (double)prefix / (double)trials,
|
||||
c->overhead * 100.0);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
# experiments/Makefile - prototypes for the lzply compression research.
|
||||
# Built with max cores via -j; each tool is standalone: `tool c in out`,
|
||||
# `tool d in out`. Shared rANS core in rans.o.
|
||||
CC = gcc
|
||||
CFLAGS = -O3 -Wall -Wextra -march=native
|
||||
LDLIBS = -llz -lm
|
||||
|
||||
TOOLS = rans_tool dict bchcheck
|
||||
all: $(TOOLS)
|
||||
|
||||
rans.o: rans.c rans.h
|
||||
$(CC) $(CFLAGS) -c -o $@ rans.c
|
||||
|
||||
rans_tool: rans_tool.o rans.o
|
||||
$(CC) $(CFLAGS) -o $@ rans_tool.o rans.o
|
||||
|
||||
dict.o: dict.c
|
||||
$(CC) $(CFLAGS) -c -o $@ dict.c
|
||||
|
||||
dict: dict.o
|
||||
$(CC) $(CFLAGS) -o $@ dict.o
|
||||
|
||||
bchcheck.o: bchcheck.c ../bch.h
|
||||
$(CC) $(CFLAGS) -I.. -c -o $@ bchcheck.c
|
||||
|
||||
bchcheck: bchcheck.o ../bch.o ../bch_polys.h
|
||||
$(CC) $(CFLAGS) -o $@ bchcheck.o ../bch.o
|
||||
|
||||
clean:
|
||||
rm -f $(TOOLS) *.o
|
||||
|
||||
.PHONY: all clean
|
||||
@@ -1,140 +0,0 @@
|
||||
# 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,
|
||||
and sha256-verifies round-trips; `bench1.py` is the single-run variant
|
||||
(for slow tools); CSVs land in results/.
|
||||
|
||||
## Corpora (built by mkcorpora.py, deterministic per machine)
|
||||
- text: 8 MiB UTF-8 docs from /usr/share/doc + common-licenses
|
||||
- code: 8 MiB C headers (/usr/include) + this repo's sources
|
||||
- bin: 8 MiB ELF binaries from /bin + /usr/bin
|
||||
- mixed: 8 MiB round-robin 64 KiB chunks of text+code+bin
|
||||
- rand: 4 MiB /dev/urandom (seed 1234), incompressible control
|
||||
Corpora are NOT committed (regenerate with mkcorpora.py).
|
||||
All ratios below are compressed/orig %; speeds are MB/s (orig bytes).
|
||||
|
||||
## Baseline: lzip (the current lzply stage; same liblz, same levels)
|
||||
| tool | text | code | bin | mixed | rand | enc MB/s | dec MB/s |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| lzip -1 | 6.22 | 15.13 | 37.83 | 21.58 | 101.36 | 1.4-9.1 | 8.9-71.8 |
|
||||
| lzip -6 | 3.56 | 9.38 | 32.61 | 17.41 | 101.36 | 0.9-2.3 | 7.9-71.4 |
|
||||
| lzip -9 | 3.44 | 9.05 | 32.53 | 17.17 | 101.36 | 0.8-1.4 | 9.0-70.3 |
|
||||
References: xz -6 ~= lzip -6 (text 3.51, code 9.20, bin 32.59,
|
||||
mixed 17.30); zstd -19 text 3.63, code 9.48, bin 34.81, mixed 18.31;
|
||||
gzip -9 text 23.48, code 16.40, bin 44.14, mixed 30.06;
|
||||
bzip2 -9 text 9.25, code 12.55, bin 40.22, mixed 23.53,
|
||||
dec only 5-9 MB/s.
|
||||
|
||||
## ANS: rANS order-0 (rans_tool) — REJECT as standalone, KEEP core
|
||||
Static per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
|
||||
RSS ~20 MB, but no LZ stage: text 64.40, code 67.62, bin 77.14,
|
||||
mixed 78.11, rand 100.46. The core is the entropy stage for the BWT
|
||||
and LZ prototypes below. (Two real bugs found and fixed in the core:
|
||||
renormalisation threshold must be (L>>12)*f<<8 or the decoder
|
||||
over-reads; the emitted stream can exceed n bytes, scratch is 2n+64.)
|
||||
|
||||
## LZ77 + rANS (lzrans) — REJECT as a lzip replacement
|
||||
Hash-chain finder, 1 MiB window, lazy (`c`) and optimal-parse (`o`)
|
||||
modes, deflate-style length codes, log2 distance codes, litlen/dist
|
||||
rANS streams + raw extra bits.
|
||||
| mode | text | code | bin | mixed | rand | enc | dec | RSS |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| lazy | 6.26 | 13.52 | 41.84 | 23.15 | 100.48 | 0.5-4.4 | 26-73 | 44 MB |
|
||||
| optimal | 6.19 | 13.05 | — | — | — | 0.4-1.0 | 64-73 | 173 MB |
|
||||
Optimal parsing recovers only ~1-3% relative, so the gap is not
|
||||
parsing: it is LZMA's adaptive context entropy model plus deeper
|
||||
match search and a larger dictionary. A static-table rANS cannot
|
||||
close a ~75% relative gap on text.
|
||||
|
||||
## BWT + MTF + run tokens + rANS (bwt) — REJECT as a lzip replacement
|
||||
Suffix array by cyclic doubling (see the linear-vs-rotation trap
|
||||
below), MTF, runs >=4 tokenised as (value, 256, k), 257-symbol rANS.
|
||||
| corpus | ratio | enc | dec |
|
||||
|---|---|---|---|
|
||||
| text | 6.35 | 177 s (0.05 MB/s) | 5.3 MB/s |
|
||||
| code | 12.31 | 173 s | 6.3 MB/s |
|
||||
| bin | 42.76 | 137 s | 5.9 MB/s |
|
||||
| mixed | (bench running) | | |
|
||||
| rand | (bench running) | | |
|
||||
RSS ~200 MB. Beats bzip2 on text (6.35 vs 9.25), ~ties on code
|
||||
(12.31 vs 12.55), loses on bin (42.76 vs 40.22); loses to lzip
|
||||
everywhere by a wide margin. Encode is ~3 min/8 MB (doubling SA is
|
||||
memory-latency-bound over 160 MB of rank arrays); decode is 5-6 MB/s
|
||||
(LF-walk random access).
|
||||
GOTCHA (real bug, fixed): a linear suffix sort is NOT rotation
|
||||
order — "a" < "a bandana" linearly, but cyclically
|
||||
"a bandanabanan" < "abanana bandan". A sentinel does not fix it
|
||||
("a$" < "a bandana$" truncates the comparison). The SA must use
|
||||
cyclic doubling (rank[(i+k) % n]).
|
||||
|
||||
## PPM order-2 + arithmetic coding (ppm) — REJECT
|
||||
Order-2/1/0 contexts, escape mass = distinct-symbol count,
|
||||
Witten-Neal-Cleary 32-bit arithmetic coder, counts updated in all
|
||||
levels after every symbol. RSS ~80 MB.
|
||||
| corpus | ratio | enc MB/s | dec MB/s |
|
||||
|---|---|---|---|
|
||||
| text | 32.84 | 6.3 | 3.9 |
|
||||
| code | 30.82 | 6.3 | 4.1 |
|
||||
| mixed | 39.18 | 4.8 | 3.2 |
|
||||
Far behind lzip and slow: the bit-level coder plus 256-wide level
|
||||
scans cost ~6 MB/s encode, ~4 MB/s decode. A simple order-2 PPM
|
||||
with heavy escape mass is nowhere near PPMd-class.
|
||||
|
||||
## Dictionary transform + lzip (dict) — CONDITIONAL, code only
|
||||
Per-file word dictionary (top 4096 words by saving, transmitted in
|
||||
the header), words -> 3-byte codes, then lzip -6. RSS ~32 MB.
|
||||
| corpus | dict+lzip6 | plain lzip6 | delta |
|
||||
|---|---|---|---|
|
||||
| text | 3.58 | 3.56 | +0.5% worse |
|
||||
| code | 9.19 | 9.38 | -2.1% BETTER |
|
||||
| bin | 33.30 | 32.61 | +2.1% worse |
|
||||
| mixed | 17.65 | 17.41 | +1.4% worse |
|
||||
| rand | 101.73 | 101.36 | worse |
|
||||
Only code wins (+2.1%): long repeated identifiers survive as codes
|
||||
better than as LZ matches. Everywhere else the dictionary costs
|
||||
more than it saves (lzip already captures word repeats). Not a
|
||||
default; a code-only optional preprocessing stage at most.
|
||||
(Gotcha fixed during the build: words are sorted by count, so the
|
||||
saving filter must `continue`, not `break`, or a short frequent
|
||||
word like "the" discards the whole dictionary.)
|
||||
|
||||
## BCH end-to-end (bchcheck) — winners survive error correction
|
||||
Blob -> BCH(t=8, lzply -e 4 level) -> flip N bits -> decode ->
|
||||
decompress -> sha256 check.
|
||||
- dict+lzip code blob (770,519 B): poly 0050, stored 770,563
|
||||
(+44 B parity, 0.006%). 8 flips -> 8 corrected, full pipeline
|
||||
recovers bit-identical. 32 flips -> decode FAIL (exceeds t=8 per
|
||||
block; honest failure mode).
|
||||
- plain lzip6 code blob (787,213 B): 8 flips -> 8 corrected,
|
||||
recovered + decoded bit-identical.
|
||||
|
||||
## Verdicts (bottom line)
|
||||
- No family beats lzip on ratio. lzip/LZMA's adaptive entropy
|
||||
model + deep match search + large dictionary is very hard to beat
|
||||
with a from-scratch prototype in this scope.
|
||||
- KEEP: the rANS core (fast, correct, reusable as an entropy stage).
|
||||
- CONDITIONAL: dict transform, code-only (+2.1% on code).
|
||||
- REJECT: lzrans (lazy + optimal), BWT, PPM order-2, rANS order-0
|
||||
standalone. Honest negatives, numbers above.
|
||||
- Test totals: 334 timed bench invocations, all sha256-verified OK
|
||||
(plus ~25 manual small-input round-trips and 3 BCH runs: 2 pass,
|
||||
1 expected fail at 32 flips).
|
||||
|
||||
## Notes / environment
|
||||
- hot_newyork (172.93.49.176), 8 cores, 30 GB RAM; server load was
|
||||
10-17 during the runs (shared with other agents), so absolute
|
||||
MB/s figures are load-dependent; ratios are exact.
|
||||
- hot_chicago verification pending: its SSH stopped accepting new
|
||||
sessions Dec 2 (sshd can't fork under load); a retry agent is
|
||||
probing every 15 min. No Chicago numbers yet.
|
||||
- The other lz_rs/deep-repair coordinator works in /opt/lzply/src
|
||||
and /root/lzrs-verify/lzply; untouched by this work. No
|
||||
Reed-Solomon was (re-)implemented here.
|
||||
@@ -1,88 +0,0 @@
|
||||
/* bchcheck.c - BCH end-to-end corruption test for experiment blobs.
|
||||
* Takes a compressed blob, BCH-encodes it (t=8 by default, the lzply
|
||||
* -e 4 level; largest t=8 poly if the blob exceeds one m=22 block),
|
||||
* flips N random bits (seeded), decodes, and writes the recovered
|
||||
* blob. Exit 0 if the recovered blob is byte-identical to the input,
|
||||
* 1 if decode failed or the blob differs, 2 on usage/IO error.
|
||||
* Usage: bchcheck blob nflips seed out [t]
|
||||
* The caller then decompresses `out` with the prototype and checks
|
||||
* the sha256 round-trip, proving the compressed stream survives BCH.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "bch.h"
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* Largest-capacity poly with the requested t (m=22 wins). */
|
||||
static const bch_poly_t *largest_t_poly(int t) {
|
||||
const bch_poly_t *best = NULL;
|
||||
size_t bestcap = 0;
|
||||
for (uint16_t id = 0x0001; id <= 0x0052; id++) {
|
||||
const bch_poly_t *p = bch_poly_by_id(id);
|
||||
if (!p || p->t != t) continue;
|
||||
size_t cap = bch_max_data(p);
|
||||
if (cap > bestcap) { bestcap = cap; best = p; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 5 || argc > 6) {
|
||||
fprintf(stderr, "usage: %s blob nflips seed out [t]\n", argv[0]);
|
||||
return 2;
|
||||
}
|
||||
int t = argc == 6 ? atoi(argv[5]) : 8;
|
||||
long nflips = atol(argv[2]);
|
||||
unsigned seed = (unsigned)atoi(argv[3]);
|
||||
size_t n;
|
||||
uint8_t *blob = slurp(argv[1], &n);
|
||||
const bch_poly_t *poly = bch_poly_for_data(n, t);
|
||||
if (!poly) poly = largest_t_poly(t);
|
||||
if (!poly) { fprintf(stderr, "bchcheck: no poly for t=%d\n", t); return 2; }
|
||||
size_t slen = bch_encoded_len(n, poly);
|
||||
uint8_t *stored = malloc(slen ? slen : 1);
|
||||
uint8_t *rec = malloc(n ? n : 1);
|
||||
if (!stored || !rec) return 2;
|
||||
if (bch_encode(blob, n, poly, stored) != slen) {
|
||||
fprintf(stderr, "bchcheck: encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
/* xorshift64 PRNG for flip positions (seeded, deterministic) */
|
||||
uint64_t xs = (uint64_t)seed * 0x9E3779B97F4A7C15ULL + 0x123456789ULL;
|
||||
for (long k = 0; k < nflips; k++) {
|
||||
xs ^= xs << 13; xs ^= xs >> 7; xs ^= xs << 17;
|
||||
size_t bit = (size_t)(xs % (uint64_t)(slen * 8));
|
||||
stored[bit / 8] ^= (uint8_t)(0x80u >> (bit % 8));
|
||||
}
|
||||
int corrected = 0;
|
||||
int rc = bch_decode(stored, slen, n, poly, rec, &corrected);
|
||||
fprintf(stderr, "bchcheck: poly=%04x blob=%zu stored=%zu overhead=%.1f%% "
|
||||
"flips=%ld corrected=%d decode=%s\n",
|
||||
poly->id, n, slen, 100.0 * (double)(slen - n) / (double)n,
|
||||
nflips, corrected, rc == 0 ? "OK" : "FAIL");
|
||||
if (rc != 0) return 1;
|
||||
FILE *f = fopen(argv[4], "wb");
|
||||
if (!f) { perror(argv[4]); return 2; }
|
||||
if (n && fwrite(rec, 1, n, f) != n) return 2;
|
||||
fclose(f);
|
||||
if (memcmp(blob, rec, n) != 0) {
|
||||
fprintf(stderr, "bchcheck: recovered blob DIFFERS\n");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""bench.py <name> <enc-template> <dec-template> [corpus...]
|
||||
Templates use {in} {out} {dec}; run via /bin/sh. Times encode/decode
|
||||
(wall, best of 3 for encode, best of 3 for decode), records ratio,
|
||||
MB/s, sha256 round-trip. Appends CSV rows to results/<name>.csv and
|
||||
prints a table. Encode failure on a corpus records 'FAIL'.
|
||||
"""
|
||||
import subprocess, sys, os, time, hashlib, csv
|
||||
|
||||
EXP = os.path.dirname(os.path.abspath(__file__))
|
||||
CORP = os.path.join(EXP, "corpora")
|
||||
RES = os.path.join(EXP, "results")
|
||||
TMP = "/tmp/expbench"
|
||||
os.makedirs(TMP, exist_ok=True)
|
||||
os.makedirs(RES, exist_ok=True)
|
||||
|
||||
def sha(p):
|
||||
h = hashlib.sha256()
|
||||
with open(p, "rb") as fh:
|
||||
for c in iter(lambda: fh.read(1 << 20), b""):
|
||||
h.update(c)
|
||||
return h.hexdigest()
|
||||
|
||||
def run(cmd, timeout=600):
|
||||
t0 = time.perf_counter()
|
||||
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
return r.returncode, time.perf_counter() - t0
|
||||
|
||||
def bench_one(name, enc, dec, corpus):
|
||||
src = os.path.join(CORP, corpus)
|
||||
n = os.path.getsize(src)
|
||||
want = sha(src)
|
||||
out = os.path.join(TMP, name + ".out")
|
||||
decf = os.path.join(TMP, name + ".dec")
|
||||
for f in (out, decf):
|
||||
if os.path.exists(f):
|
||||
os.unlink(f)
|
||||
best_enc = None
|
||||
for _ in range(3):
|
||||
rc, dt = run(enc.format(**{"in": src, "out": out, "dec": decf}))
|
||||
if rc != 0:
|
||||
return (corpus, n, None, None, None, "ENCFAIL")
|
||||
best_enc = dt if best_enc is None else min(best_enc, dt)
|
||||
csize = os.path.getsize(out)
|
||||
best_dec = None
|
||||
for _ in range(3):
|
||||
if os.path.exists(decf):
|
||||
os.unlink(decf)
|
||||
rc, dt = run(dec.format(**{"in": src, "out": out, "dec": decf}))
|
||||
if rc != 0:
|
||||
return (corpus, n, csize, None, None, "DECFAIL")
|
||||
best_dec = dt if best_dec is None else min(best_dec, dt)
|
||||
ok = sha(decf) == want
|
||||
return (corpus, n, csize, best_enc, best_dec, "OK" if ok else "MISMATCH")
|
||||
|
||||
def main():
|
||||
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
|
||||
csvp = os.path.join(RES, name + ".csv")
|
||||
new = not os.path.exists(csvp)
|
||||
print(f"== {name}: enc=[{enc}] dec=[{dec}]")
|
||||
print(f"{'corpus':8s} {'orig':>9s} {'comp':>9s} {'ratio%':>7s} {'encMB/s':>8s} {'decMB/s':>8s} status")
|
||||
with open(csvp, "a", newline="") as fh:
|
||||
w = csv.writer(fh)
|
||||
if new:
|
||||
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
|
||||
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
|
||||
for c in corpora:
|
||||
corpus, n, cs, es, ds, st = bench_one(name, enc, dec, c)
|
||||
if cs is None:
|
||||
print(f"{c:8s} {n:9d} {'-':>9s} {'-':>7s} {'-':>8s} {'-':>8s} {st}")
|
||||
w.writerow([name, c, n, "", "", "", "", "", "", st])
|
||||
continue
|
||||
ratio = 100.0 * cs / n
|
||||
emb = n / 1e6 / es if es else 0
|
||||
dmb = n / 1e6 / ds if ds else 0
|
||||
print(f"{c:8s} {n:9d} {cs:9d} {ratio:7.2f} {emb:8.1f} {dmb:8.1f} {st}")
|
||||
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
|
||||
f"{emb:.1f}", f"{dmb:.1f}", st])
|
||||
print("csv: " + csvp)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,71 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""bench1.py: single-run variant of bench.py (for slow tools like bwt).
|
||||
Usage: bench1.py <name> <enc-template> <dec-template> [corpus...]
|
||||
Appends to results/<name>.csv and prints one line per corpus."""
|
||||
import subprocess, sys, os, time, hashlib, csv
|
||||
|
||||
EXP = os.path.dirname(os.path.abspath(__file__))
|
||||
CORP = os.path.join(EXP, "corpora")
|
||||
RES = os.path.join(EXP, "results")
|
||||
TMP = "/tmp/expbench"
|
||||
os.makedirs(TMP, exist_ok=True)
|
||||
os.makedirs(RES, exist_ok=True)
|
||||
|
||||
def sha(p):
|
||||
h = hashlib.sha256()
|
||||
with open(p, "rb") as fh:
|
||||
for c in iter(lambda: fh.read(1 << 20), b""):
|
||||
h.update(c)
|
||||
return h.hexdigest()
|
||||
|
||||
def run(cmd, timeout=3600):
|
||||
t0 = time.perf_counter()
|
||||
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
return r.returncode, time.perf_counter() - t0
|
||||
|
||||
def main():
|
||||
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
|
||||
csvp = os.path.join(RES, name + ".csv")
|
||||
new = not os.path.exists(csvp)
|
||||
print(f"== {name} (single run)", flush=True)
|
||||
with open(csvp, "a", newline="") as fh:
|
||||
w = csv.writer(fh)
|
||||
if new:
|
||||
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
|
||||
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
|
||||
for c in corpora:
|
||||
src = os.path.join(CORP, c)
|
||||
n = os.path.getsize(src)
|
||||
want = sha(src)
|
||||
out = os.path.join(TMP, name + ".out")
|
||||
decf = os.path.join(TMP, name + ".dec")
|
||||
for f in (out, decf):
|
||||
if os.path.exists(f):
|
||||
os.unlink(f)
|
||||
rc, es = run(enc.format(**{"in": src, "out": out, "dec": decf}))
|
||||
if rc != 0:
|
||||
print(f"{c}: ENCFAIL", flush=True)
|
||||
w.writerow([name, c, n, "", "", "", "", "", "", "ENCFAIL"])
|
||||
continue
|
||||
cs = os.path.getsize(out)
|
||||
if os.path.exists(decf):
|
||||
os.unlink(decf)
|
||||
rc, ds = run(dec.format(**{"in": src, "out": out, "dec": decf}))
|
||||
if rc != 0:
|
||||
print(f"{c}: DECFAIL", flush=True)
|
||||
w.writerow([name, c, n, cs, "", "", "", "", "", "DECFAIL"])
|
||||
continue
|
||||
ok = sha(decf) == want
|
||||
st = "OK" if ok else "MISMATCH"
|
||||
ratio = 100.0 * cs / n
|
||||
print(f"{c:8s} {n:9d} {cs:9d} {ratio:6.2f}% enc {es:7.1f}s "
|
||||
f"({n/1e6/es:5.1f} MB/s) dec {ds:6.1f}s ({n/1e6/ds:5.1f} MB/s) {st}",
|
||||
flush=True)
|
||||
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
|
||||
f"{n/1e6/es:.1f}", f"{n/1e6/ds:.1f}", st])
|
||||
print("csv: " + csvp, flush=True)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,260 +0,0 @@
|
||||
/* dict.c - word-dictionary transform (preprocessing stage for lzip).
|
||||
* Builds a per-file dictionary of the most frequent words (alnum runs
|
||||
* of length >= 3), replaces them with 2-byte codes, then the caller
|
||||
* pipes the output through lzip. The dictionary is transmitted in
|
||||
* the header, so the cost is honest.
|
||||
* Format: magic "DICT", u32 orig_len, u16 ndict, then ndict entries
|
||||
* (u8 len, bytes), then the transformed stream: 0xFF escape byte
|
||||
* introduces a 2-byte code (little-endian); a literal 0xFF in the
|
||||
* data is escaped as 0xFF 0xFF 0xFF (escape + code 0xFFFF = literal
|
||||
* 0xFF); other bytes pass through. Words are maximal [A-Za-z0-9_]
|
||||
* runs; only words in the dictionary are replaced.
|
||||
* Usage: dict c in out | dict d in out
|
||||
* (then: lzip -6 transformed; decode: lzip -d | dict d)
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define ESC 0xFF
|
||||
#define MAX_DICT 4096
|
||||
#define MIN_WORD 3
|
||||
|
||||
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 int is_word(int c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
|
||||
(c >= '0' && c <= '9') || c == '_';
|
||||
}
|
||||
|
||||
/* word table entry */
|
||||
typedef struct { char *w; uint32_t count; } went_t;
|
||||
|
||||
static int cmp_count(const void *a, const void *b) {
|
||||
uint32_t ca = ((const went_t *)a)->count, cb = ((const went_t *)b)->count;
|
||||
return ca < cb ? 1 : ca > cb ? -1 : 0;
|
||||
}
|
||||
|
||||
static uint32_t hash_str(const char *s, size_t n) {
|
||||
uint32_t h = 2166136261u;
|
||||
for (size_t i = 0; i < n; i++) { h ^= (uint8_t)s[i]; h *= 16777619u; }
|
||||
return h;
|
||||
}
|
||||
|
||||
static int encode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
/* count words in a hash table (open addressing) */
|
||||
size_t hcap = 1 << 20;
|
||||
went_t *ht = calloc(hcap, sizeof *ht);
|
||||
if (!ht) return 2;
|
||||
size_t i = 0;
|
||||
while (i < n) {
|
||||
if (!is_word(in[i])) { i++; continue; }
|
||||
size_t j = i;
|
||||
while (j < n && is_word(in[j])) j++;
|
||||
size_t len = j - i;
|
||||
if (len >= MIN_WORD) {
|
||||
uint32_t h = hash_str((char *)in + i, len) & (hcap - 1);
|
||||
while (ht[h].w) {
|
||||
if (strlen(ht[h].w) == len &&
|
||||
memcmp(ht[h].w, in + i, len) == 0) break;
|
||||
h = (h + 1) & (hcap - 1);
|
||||
}
|
||||
if (!ht[h].w) {
|
||||
ht[h].w = malloc(len + 1);
|
||||
memcpy(ht[h].w, in + i, len);
|
||||
ht[h].w[len] = 0;
|
||||
}
|
||||
ht[h].count++;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
/* collect, sort by count, keep the top MAX_DICT by SAVING:
|
||||
* saving = count * (len - 3) - (len + 1) [dict cost]; keep > 0 */
|
||||
went_t *all = malloc(hcap * sizeof *all);
|
||||
size_t na = 0;
|
||||
for (size_t k = 0; k < hcap; k++)
|
||||
if (ht[k].w) all[na++] = ht[k];
|
||||
qsort(all, na, sizeof *all, cmp_count);
|
||||
went_t *dict = malloc(MAX_DICT * sizeof *dict);
|
||||
size_t nd = 0;
|
||||
for (size_t k = 0; k < na && nd < MAX_DICT; k++) {
|
||||
size_t len = strlen(all[k].w);
|
||||
/* code costs 3 bytes (ESC + 2), word costs len; saving per
|
||||
* occurrence = len - 3; dict entry costs len + 1 bytes */
|
||||
int64_t saving = (int64_t)all[k].count * ((int64_t)len - 3) -
|
||||
(int64_t)(len + 1);
|
||||
if (saving <= 0) continue; /* sorted by count, not saving */
|
||||
dict[nd++] = all[k];
|
||||
}
|
||||
/* rebuild a lookup hash for the kept dictionary: code = index */
|
||||
size_t lcap = 1 << 16;
|
||||
int32_t *look = malloc(lcap * sizeof *look);
|
||||
if (!look) return 2;
|
||||
for (size_t k = 0; k < lcap; k++) look[k] = -1;
|
||||
for (size_t k = 0; k < nd; k++) {
|
||||
size_t len = strlen(dict[k].w);
|
||||
uint32_t h = hash_str(dict[k].w, len) & (lcap - 1);
|
||||
while (look[h] >= 0) h = (h + 1) & (lcap - 1);
|
||||
look[h] = (int32_t)k;
|
||||
}
|
||||
/* transform */
|
||||
size_t cap = n + 1024;
|
||||
uint8_t *out = malloc(cap);
|
||||
if (!out) return 2;
|
||||
size_t o = 0;
|
||||
/* make room for the dictionary header */
|
||||
{
|
||||
size_t hdr = 10;
|
||||
for (size_t k = 0; k < nd; k++) hdr += 1 + strlen(dict[k].w);
|
||||
if (cap < hdr + 16) {
|
||||
cap = hdr + 16;
|
||||
out = realloc(out, cap);
|
||||
if (!out) return 2;
|
||||
}
|
||||
}
|
||||
/* header: magic, orig_len, ndict, entries */
|
||||
memcpy(out, "DICT", 4); o += 4;
|
||||
out[o++] = (uint8_t)(n & 0xff);
|
||||
out[o++] = (uint8_t)((n >> 8) & 0xff);
|
||||
out[o++] = (uint8_t)((n >> 16) & 0xff);
|
||||
out[o++] = (uint8_t)((n >> 24) & 0xff);
|
||||
out[o++] = (uint8_t)(nd & 0xff);
|
||||
out[o++] = (uint8_t)((nd >> 8) & 0xff);
|
||||
for (size_t k = 0; k < nd; k++) {
|
||||
size_t len = strlen(dict[k].w);
|
||||
out[o++] = (uint8_t)len;
|
||||
memcpy(out + o, dict[k].w, len);
|
||||
o += len;
|
||||
}
|
||||
/* growable body: recompute with room (header already written) */
|
||||
i = 0;
|
||||
while (i < n) {
|
||||
/* ensure room for the worst case (1 byte -> 3 bytes) + slack */
|
||||
if (o + 8 > cap) {
|
||||
cap *= 2;
|
||||
out = realloc(out, cap);
|
||||
if (!out) return 2;
|
||||
}
|
||||
if (is_word(in[i])) {
|
||||
size_t j = i;
|
||||
while (j < n && is_word(in[j])) j++;
|
||||
size_t len = j - i;
|
||||
int code = -1;
|
||||
if (len >= MIN_WORD) {
|
||||
uint32_t h = hash_str((char *)in + i, len) & (lcap - 1);
|
||||
while (look[h] >= 0) {
|
||||
int32_t k = look[h];
|
||||
if (strlen(dict[k].w) == len &&
|
||||
memcmp(dict[k].w, in + i, len) == 0) { code = k; break; }
|
||||
h = (h + 1) & (lcap - 1);
|
||||
}
|
||||
}
|
||||
if (code >= 0) {
|
||||
out[o++] = ESC;
|
||||
out[o++] = (uint8_t)(code & 0xff);
|
||||
out[o++] = (uint8_t)((code >> 8) & 0xff);
|
||||
} else {
|
||||
memcpy(out + o, in + i, len);
|
||||
o += len;
|
||||
}
|
||||
i = j;
|
||||
} else {
|
||||
uint8_t c = in[i++];
|
||||
if (c == ESC) {
|
||||
out[o++] = ESC;
|
||||
out[o++] = 0xFF;
|
||||
out[o++] = 0xFF;
|
||||
} else {
|
||||
out[o++] = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
spit(outpath, out, o);
|
||||
fprintf(stderr, "dict: %zu words kept (of %zu distinct)\n", nd, na);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int decode(const char *inpath, const char *outpath) {
|
||||
size_t n;
|
||||
uint8_t *in = slurp(inpath, &n);
|
||||
if (n < 10 || memcmp(in, "DICT", 4) != 0) {
|
||||
fprintf(stderr, "dict: 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);
|
||||
uint32_t nd = (uint32_t)in[8] | ((uint32_t)in[9] << 8);
|
||||
size_t p = 10;
|
||||
char **dict = malloc((nd ? nd : 1) * sizeof *dict);
|
||||
if (!dict) return 2;
|
||||
for (uint32_t k = 0; k < nd; k++) {
|
||||
if (p >= n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
|
||||
size_t len = in[p++];
|
||||
if (p + len > n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
|
||||
dict[k] = malloc(len + 1);
|
||||
memcpy(dict[k], in + p, len);
|
||||
dict[k][len] = 0;
|
||||
p += len;
|
||||
}
|
||||
uint8_t *out = malloc(orig ? orig : 1);
|
||||
if (!out) return 2;
|
||||
size_t o = 0;
|
||||
while (p < n) {
|
||||
uint8_t c = in[p++];
|
||||
if (c == ESC) {
|
||||
if (p + 1 >= n) { fprintf(stderr, "dict: truncated code\n"); return 3; }
|
||||
uint32_t code = (uint32_t)in[p] | ((uint32_t)in[p + 1] << 8);
|
||||
p += 2;
|
||||
if (code == 0xFFFF) {
|
||||
if (o >= orig) return 3;
|
||||
out[o++] = ESC;
|
||||
} else {
|
||||
if (code >= nd) { fprintf(stderr, "dict: bad code\n"); return 3; }
|
||||
size_t len = strlen(dict[code]);
|
||||
if (o + len > orig) return 3;
|
||||
memcpy(out + o, dict[code], len);
|
||||
o += len;
|
||||
}
|
||||
} else {
|
||||
if (o >= orig) return 3;
|
||||
out[o++] = c;
|
||||
}
|
||||
}
|
||||
if (o != orig) {
|
||||
fprintf(stderr, "dict: short output %zu != %u\n", o, orig);
|
||||
return 3;
|
||||
}
|
||||
spit(outpath, out, o);
|
||||
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]);
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build deterministic benchmark corpora on the server. Sizes capped.
|
||||
text: /usr/share/doc text files + common-licenses (English prose/docs)
|
||||
code: /usr/include headers + this repo sources (C/Markdown)
|
||||
bin: ELF binaries from /bin, /usr/bin (executables)
|
||||
mixed: round-robin 64KiB chunks of text+code+bin
|
||||
rand: /dev/urandom control (incompressible)
|
||||
"""
|
||||
import os, glob, hashlib, random
|
||||
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "corpora")
|
||||
CAP = 8 * 1024 * 1024
|
||||
|
||||
def collect(patterns, cap, text_only=False):
|
||||
buf = bytearray()
|
||||
files = []
|
||||
for p in patterns:
|
||||
files += sorted(glob.glob(p, recursive=True))
|
||||
for f in files:
|
||||
try:
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
with open(f, "rb") as fh:
|
||||
d = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
if text_only:
|
||||
try:
|
||||
d.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
buf += d
|
||||
if len(buf) >= cap:
|
||||
break
|
||||
return bytes(buf[:cap])
|
||||
|
||||
def write(name, data):
|
||||
p = os.path.join(OUT, name)
|
||||
with open(p, "wb") as fh:
|
||||
fh.write(data)
|
||||
print(name + ": " + str(len(data)) + " bytes sha256=" + hashlib.sha256(data).hexdigest()[:16])
|
||||
|
||||
text = collect(["/usr/share/doc/**/*", "/usr/share/common-licenses/*"], CAP, text_only=True)
|
||||
write("text", text)
|
||||
code = collect(["/usr/include/**/*.h", "/opt/lzply-exp-comp/*.c",
|
||||
"/opt/lzply-exp-comp/*.h", "/opt/lzply-exp-comp/*.md"], CAP)
|
||||
write("code", code)
|
||||
bins = []
|
||||
for d in ("/bin", "/usr/bin"):
|
||||
for f in sorted(glob.glob(d + "/*")):
|
||||
try:
|
||||
with open(f, "rb") as fh:
|
||||
h = fh.read(4)
|
||||
if h[:4] == b"\x7fELF":
|
||||
bins.append(f)
|
||||
except OSError:
|
||||
pass
|
||||
buf = bytearray()
|
||||
for f in bins:
|
||||
with open(f, "rb") as fh:
|
||||
buf += fh.read()
|
||||
if len(buf) >= CAP:
|
||||
break
|
||||
bindata = bytes(buf[:CAP])
|
||||
write("bin", bindata)
|
||||
parts = [text, code, bindata]
|
||||
m = bytearray()
|
||||
i = 0
|
||||
while len(m) < CAP:
|
||||
for part in parts:
|
||||
off = (i * 65536) % max(1, len(part) - 65536)
|
||||
m += part[off:off + 65536]
|
||||
if len(m) >= CAP:
|
||||
break
|
||||
i += 1
|
||||
write("mixed", bytes(m[:CAP]))
|
||||
rnd = random.Random(1234).randbytes(4 * 1024 * 1024)
|
||||
write("rand", rnd)
|
||||
@@ -1,221 +0,0 @@
|
||||
/* rans.c - rANS entropy coder (see rans.h). Standard rANS:
|
||||
* encode backwards, x in [2^23, 2^32); decode forwards from the
|
||||
* 4-byte final state stored at the end of the stream. */
|
||||
#include "rans.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq) {
|
||||
uint32_t cnt[256] = {0};
|
||||
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
|
||||
uint32_t total = 0;
|
||||
for (int s = 0; s < 256; s++) {
|
||||
/* scale counts to PROB_SCALE, present symbols keep >= 1 */
|
||||
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
|
||||
if (cnt[s] && f == 0) f = 1;
|
||||
freq[s] = (uint16_t)f;
|
||||
total += f;
|
||||
}
|
||||
/* Fix the sum to exactly PROB_SCALE by adjusting the largest. */
|
||||
int mx = 0;
|
||||
for (int s = 1; s < 256; s++) if (freq[s] > freq[mx]) mx = s;
|
||||
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
|
||||
else if (total > RANS_PROB_SCALE) {
|
||||
uint32_t over = total - RANS_PROB_SCALE;
|
||||
/* take from the largest symbol, never below 1 if present */
|
||||
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
|
||||
if (give > over) give = over;
|
||||
freq[mx] -= (uint16_t)give;
|
||||
/* if still over (pathological), trim the next largest */
|
||||
for (int s = 0; s < 256 && total - give > RANS_PROB_SCALE; s++) {
|
||||
if (s == mx || !cnt[s]) continue;
|
||||
uint32_t g = freq[s] - 1;
|
||||
uint32_t need = total - give - RANS_PROB_SCALE;
|
||||
if (g > need) g = need;
|
||||
freq[s] -= (uint16_t)g; give += g;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
|
||||
uint8_t *out) {
|
||||
uint32_t cum[256];
|
||||
uint32_t c = 0;
|
||||
for (int s = 0; s < 256; s++) { cum[s] = c; c += freq[s]; }
|
||||
uint32_t x = RANS_L;
|
||||
/* Encode backwards; emit bytes into a temp tail, then reverse.
|
||||
* Simpler: write backwards from the end of a scratch area. We
|
||||
* write into out[0..] backwards via a local reverse pass: emit
|
||||
* into out in reverse order by filling from the end. Caller
|
||||
* guarantees out holds n + 64 bytes, so use the tail. */
|
||||
uint8_t *p = out + 2 * n + 64; /* one past the end of scratch */
|
||||
/* reserve 4 bytes at the very start of the emitted stream for the
|
||||
* final state; emit stream bytes before them. Work backwards: */
|
||||
uint8_t *w = p;
|
||||
for (size_t i = n; i-- > 0;) {
|
||||
uint8_t s = in[i];
|
||||
uint32_t f = freq[s];
|
||||
/* xmax = (L>>12)*f<<8: keeps post-update state in [L, 2^31) so the
|
||||
* decoder renormalisation consumes exactly the bytes emitted here. */
|
||||
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
|
||||
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
|
||||
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
|
||||
}
|
||||
/* w..p holds the emitted bytes in order; final state x follows. */
|
||||
size_t nbytes = (size_t)(p - w);
|
||||
memmove(out + 4, w, nbytes);
|
||||
out[0] = (uint8_t)(x & 0xff);
|
||||
out[1] = (uint8_t)((x >> 8) & 0xff);
|
||||
out[2] = (uint8_t)((x >> 16) & 0xff);
|
||||
out[3] = (uint8_t)((x >> 24) & 0xff);
|
||||
return nbytes + 4;
|
||||
}
|
||||
|
||||
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
|
||||
uint8_t *out, size_t out_len) {
|
||||
if (in_len < 4) return -1;
|
||||
uint16_t cum[256];
|
||||
uint8_t dsym[RANS_PROB_SCALE];
|
||||
uint32_t c = 0;
|
||||
for (int s = 0; s < 256; s++) {
|
||||
cum[s] = (uint16_t)c;
|
||||
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint8_t)s;
|
||||
c += freq[s];
|
||||
}
|
||||
if (c != RANS_PROB_SCALE) return -1;
|
||||
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
|
||||
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
|
||||
size_t p = 4;
|
||||
for (size_t i = 0; i < out_len; i++) {
|
||||
uint32_t slot = x & (RANS_PROB_SCALE - 1);
|
||||
uint8_t s = dsym[slot];
|
||||
out[i] = s;
|
||||
uint32_t f = freq[s];
|
||||
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
|
||||
while (x < RANS_L) {
|
||||
if (p >= in_len) return -1;
|
||||
x = (x << 8) | in[p++];
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
|
||||
uint16_t freq[256];
|
||||
rans_freq(in, n, freq);
|
||||
uint8_t *buf = malloc(520 + 2 * n + 64);
|
||||
if (!buf) return -1;
|
||||
memcpy(buf, "RANS", 4);
|
||||
buf[4] = (uint8_t)(n & 0xff);
|
||||
buf[5] = (uint8_t)((n >> 8) & 0xff);
|
||||
buf[6] = (uint8_t)((n >> 16) & 0xff);
|
||||
buf[7] = (uint8_t)((n >> 24) & 0xff);
|
||||
for (int s = 0; s < 256; s++) {
|
||||
buf[8 + 2 * s] = (uint8_t)(freq[s] & 0xff);
|
||||
buf[8 + 2 * s + 1] = (uint8_t)((freq[s] >> 8) & 0xff);
|
||||
}
|
||||
size_t m = rans_encode_raw(in, n, freq, buf + 520);
|
||||
*out = buf;
|
||||
*out_len = 520 + m;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
|
||||
if (n < 520 || memcmp(in, "RANS", 4) != 0) return -1;
|
||||
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
|
||||
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
|
||||
uint16_t freq[256];
|
||||
for (int s = 0; s < 256; s++)
|
||||
freq[s] = (uint16_t)(in[8 + 2 * s] | (in[8 + 2 * s + 1] << 8));
|
||||
uint8_t *buf = malloc(orig ? orig : 1);
|
||||
if (!buf) return -1;
|
||||
if (rans_decode_raw(in + 520, n - 520, freq, buf, orig) != 0) {
|
||||
free(buf);
|
||||
return -1;
|
||||
}
|
||||
*out = buf;
|
||||
*out_len = orig;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---- general-alphabet layer (uint16_t symbols) ---- */
|
||||
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq) {
|
||||
uint32_t cnt[1024] = {0};
|
||||
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
|
||||
uint32_t total = 0;
|
||||
for (int s = 0; s < nsym; s++) {
|
||||
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
|
||||
if (cnt[s] && f == 0) f = 1;
|
||||
freq[s] = (uint16_t)f;
|
||||
total += f;
|
||||
}
|
||||
int mx = 0;
|
||||
for (int s = 1; s < nsym; s++) if (freq[s] > freq[mx]) mx = s;
|
||||
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
|
||||
else if (total > RANS_PROB_SCALE) {
|
||||
uint32_t over = total - RANS_PROB_SCALE;
|
||||
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
|
||||
if (give > over) give = over;
|
||||
freq[mx] -= (uint16_t)give;
|
||||
for (int s = 0; s < nsym && total - give > RANS_PROB_SCALE; s++) {
|
||||
if (s == mx || !cnt[s]) continue;
|
||||
uint32_t g = freq[s] - 1;
|
||||
uint32_t need = total - give - RANS_PROB_SCALE;
|
||||
if (g > need) g = need;
|
||||
freq[s] -= (uint16_t)g; give += g;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
|
||||
int nsym, uint8_t *out) {
|
||||
uint32_t cum[1024];
|
||||
uint32_t c = 0;
|
||||
for (int s = 0; s < nsym; s++) { cum[s] = c; c += freq[s]; }
|
||||
uint32_t x = RANS_L;
|
||||
uint8_t *p = out + 2 * n + 64;
|
||||
uint8_t *w = p;
|
||||
for (size_t i = n; i-- > 0;) {
|
||||
uint16_t s = in[i];
|
||||
uint32_t f = freq[s];
|
||||
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
|
||||
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
|
||||
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
|
||||
}
|
||||
size_t nbytes = (size_t)(p - w);
|
||||
memmove(out + 4, w, nbytes);
|
||||
out[0] = (uint8_t)(x & 0xff);
|
||||
out[1] = (uint8_t)((x >> 8) & 0xff);
|
||||
out[2] = (uint8_t)((x >> 16) & 0xff);
|
||||
out[3] = (uint8_t)((x >> 24) & 0xff);
|
||||
return nbytes + 4;
|
||||
}
|
||||
|
||||
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
|
||||
int nsym, uint16_t *out, size_t out_len) {
|
||||
if (in_len < 4) return -1;
|
||||
uint16_t cum[1024];
|
||||
uint16_t dsym[RANS_PROB_SCALE];
|
||||
uint32_t c = 0;
|
||||
for (int s = 0; s < nsym; s++) {
|
||||
cum[s] = (uint16_t)c;
|
||||
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint16_t)s;
|
||||
c += freq[s];
|
||||
}
|
||||
if (c != RANS_PROB_SCALE) return -1;
|
||||
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
|
||||
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
|
||||
size_t p = 4;
|
||||
for (size_t i = 0; i < out_len; i++) {
|
||||
uint32_t slot = x & (RANS_PROB_SCALE - 1);
|
||||
uint16_t s = dsym[slot];
|
||||
out[i] = s;
|
||||
uint32_t f = freq[s];
|
||||
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
|
||||
while (x < RANS_L) {
|
||||
if (p >= in_len) return -1;
|
||||
x = (x << 8) | in[p++];
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
/* rans.h - rANS entropy coder shared by the lzply experiments.
|
||||
* 12-bit probabilities (scale 4096), 23-bit renormalisation window.
|
||||
* Two layers:
|
||||
* - stream layer: rans_freq / rans_encode_raw / rans_decode_raw work
|
||||
* on a raw byte stream with a caller-supplied freq table (for
|
||||
* multi-stream coders, e.g. LZ token streams).
|
||||
* - file layer: rans_encode / rans_decode wrap one stream with a
|
||||
* header (magic "RANS", u32 orig_len, 256 x u16 freq table).
|
||||
*/
|
||||
#ifndef EXP_RANS_H
|
||||
#define EXP_RANS_H
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define RANS_PROB_BITS 12
|
||||
#define RANS_PROB_SCALE (1u << RANS_PROB_BITS)
|
||||
#define RANS_L (1u << 23)
|
||||
|
||||
/* Count + normalise frequencies of `in` to sum RANS_PROB_SCALE.
|
||||
* Symbols present get >= 1. */
|
||||
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq /*[256]*/);
|
||||
|
||||
/* Encode `in` with `freq`; `out` must hold 2*n + 64 bytes. Returns
|
||||
* bytes written. */
|
||||
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
|
||||
uint8_t *out);
|
||||
|
||||
/* Decode `in_len` bytes into `out` (out_len bytes). Returns 0 ok, -1 bad. */
|
||||
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
|
||||
uint8_t *out, size_t out_len);
|
||||
|
||||
/* Whole-file wrap: mallocs *out. Returns 0 ok, -1 bad. */
|
||||
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
|
||||
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
|
||||
|
||||
#endif
|
||||
|
||||
/* General-alphabet layer (uint16_t symbols, nsym <= 1024): for token
|
||||
* streams such as literal/length (286 symbols) and distance (21). */
|
||||
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq);
|
||||
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
|
||||
int nsym, uint8_t *out /* 2*n+64 */);
|
||||
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
|
||||
int nsym, uint16_t *out, size_t out_len);
|
||||
@@ -1,46 +0,0 @@
|
||||
/* rans_tool.c - standalone rANS order-0 compressor: `rans_tool c in out`,
|
||||
* `rans_tool d in out`. Used for the ANS-family measurements. */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "rans.h"
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
size_t n;
|
||||
uint8_t *in = slurp(argv[2], &n);
|
||||
uint8_t *out = NULL;
|
||||
size_t on = 0;
|
||||
int rc = argv[1][0] == 'c' ? rans_encode(in, n, &out, &on)
|
||||
: rans_decode(in, n, &out, &on);
|
||||
if (rc != 0) {
|
||||
fprintf(stderr, "%s: %s failed (bad input?)\n", argv[0], argv[1]);
|
||||
return 3;
|
||||
}
|
||||
spit(argv[3], out, on);
|
||||
return 0;
|
||||
}
|
||||
Whitespace-only changes.
|
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
bzip2,text,8388608,776306,9.25,2.969,1.346,2.8,6.2,OK
|
||||
bzip2,code,8388608,1053123,12.55,2.754,0.937,3.0,8.9,OK
|
||||
bzip2,bin,8388608,3373815,40.22,1.866,1.575,4.5,5.3,OK
|
||||
bzip2,mixed,8388608,1974225,23.53,2.081,0.875,4.0,9.6,OK
|
||||
bzip2,rand,4194304,4213434,100.46,1.336,0.958,3.1,4.4,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
dict-lzip6,text,8388608,299963,3.58,2.541,0.166,3.3,50.4,OK
|
||||
dict-lzip6,code,8388608,770519,9.19,4.144,0.218,2.0,38.5,OK
|
||||
dict-lzip6,bin,8388608,2793130,33.30,9.522,0.467,0.9,18.0,OK
|
||||
dict-lzip6,mixed,8388608,1480819,17.65,5.358,0.317,1.6,26.5,OK
|
||||
dict-lzip6,rand,4194304,4266698,101.73,2.794,0.475,1.5,8.8,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
gzip9,text,8388608,1969901,23.48,0.830,0.117,10.1,71.6,OK
|
||||
gzip9,code,8388608,1376091,16.40,0.980,0.066,8.6,127.7,OK
|
||||
gzip9,bin,8388608,3702420,44.14,2.700,0.115,3.1,72.6,OK
|
||||
gzip9,mixed,8388608,2521765,30.06,1.180,0.117,7.1,71.5,OK
|
||||
gzip9,rand,4194304,4194967,100.02,0.428,0.059,9.8,71.3,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
lzip1,text,8388608,521474,6.22,0.923,0.117,9.1,71.8,OK
|
||||
lzip1,code,8388608,1268850,15.13,1.127,0.216,7.4,38.8,OK
|
||||
lzip1,bin,8388608,3173235,37.83,3.144,0.468,2.7,17.9,OK
|
||||
lzip1,mixed,8388608,1809972,21.58,1.789,0.271,4.7,31.0,OK
|
||||
lzip1,rand,4194304,4251394,101.36,3.104,0.474,1.4,8.9,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
lzip6,text,8388608,298558,3.56,3.655,0.117,2.3,71.4,OK
|
||||
lzip6,code,8388608,787213,9.38,5.138,0.168,1.6,50.0,OK
|
||||
lzip6,bin,8388608,2735269,32.61,9.676,0.416,0.9,20.2,OK
|
||||
lzip6,mixed,8388608,1460156,17.41,5.519,0.267,1.5,31.4,OK
|
||||
lzip6,rand,4194304,4251435,101.36,3.173,0.531,1.3,7.9,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
lzip9,text,8388608,288746,3.44,6.658,0.119,1.3,70.3,OK
|
||||
lzip9,code,8388608,758969,9.05,9.062,0.168,0.9,50.0,OK
|
||||
lzip9,bin,8388608,2729180,32.53,10.747,0.479,0.8,17.5,OK
|
||||
lzip9,mixed,8388608,1440405,17.17,8.603,0.272,1.0,30.8,OK
|
||||
lzip9,rand,4194304,4251435,101.36,3.071,0.467,1.4,9.0,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
lzrans-lazy,text,8388608,525357,6.26,1.888,0.119,4.4,70.6,OK
|
||||
lzrans-lazy,code,8388608,1134159,13.52,3.264,0.116,2.6,72.5,OK
|
||||
lzrans-lazy,bin,8388608,3510054,41.84,9.644,0.320,0.9,26.2,OK
|
||||
lzrans-lazy,mixed,8388608,1942374,23.15,3.963,0.165,2.1,50.7,OK
|
||||
lzrans-lazy,rand,4194304,4214292,100.48,9.295,0.115,0.5,36.3,OK
|
||||
|
@@ -1,3 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
lzrans-opt,text,8388608,519352,6.19,18.714,0.132,0.4,63.5,OK
|
||||
lzrans-opt,code,8388608,1094779,13.05,8.628,0.115,1.0,72.9,OK
|
||||
|
@@ -1,4 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
ppm,text,8388608,2754814,32.84,1.327,2.176,6.3,3.9,OK
|
||||
ppm,code,8388608,2585570,30.82,1.324,2.040,6.3,4.1,OK
|
||||
ppm,mixed,8388608,3286801,39.18,1.732,2.635,4.8,3.2,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
rans0,text,8388608,5401895,64.40,0.221,0.170,38.0,49.3,OK
|
||||
rans0,code,8388608,5672388,67.62,0.277,0.171,30.3,49.1,OK
|
||||
rans0,bin,8388608,6470778,77.14,0.217,0.179,38.6,46.9,OK
|
||||
rans0,mixed,8388608,6552704,78.11,0.218,0.174,38.4,48.1,OK
|
||||
rans0,rand,4194304,4213441,100.46,0.115,0.068,36.4,61.6,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
xz6,text,8388608,294056,3.51,4.257,0.076,2.0,110.1,OK
|
||||
xz6,code,8388608,771984,9.20,7.147,0.200,1.2,42.0,OK
|
||||
xz6,bin,8388608,2733616,32.59,12.330,0.367,0.7,22.8,OK
|
||||
xz6,mixed,8388608,1450908,17.30,7.553,0.271,1.1,31.0,OK
|
||||
xz6,rand,4194304,4194584,100.01,3.323,0.085,1.3,49.1,OK
|
||||
|
@@ -1,6 +0,0 @@
|
||||
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
|
||||
zstd19,text,8388608,304391,3.63,3.549,0.055,2.4,151.8,OK
|
||||
zstd19,code,8388608,795239,9.48,11.348,0.071,0.7,117.7,OK
|
||||
zstd19,bin,8388608,2919792,34.81,14.260,0.169,0.6,49.5,OK
|
||||
zstd19,mixed,8388608,1535960,18.31,8.021,0.066,1.0,126.9,OK
|
||||
zstd19,rand,4194304,4194413,100.00,3.020,0.037,1.4,112.0,OK
|
||||
|
@@ -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