CRC16 migration (LZPL v5) + lzply_deep_repair past-t repair
CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF) per entry over the blob, stored in the LZRS v1 reserved crc16 field and in a new u16 at LZPL entry-header offset 74 (LZPL v4 -> v5, header 78 -> 80 bytes, header_crc32 now covers 76 bytes). Readers verify after error correction, before decompression; old files without a valid CRC16 are rejected cleanly with a migration error, never misdecoded. New lzply_deep_repair tool: L0 standard decode to t, L1 Chase-1 flips of least-reliable bits, L2 Chase-2 pairs, L3 two-block combine, all bounded (64 Chase-1 cands, 128 first elements, 256 blob tries, 120 s default budget). CRC16 is the oracle: every beyond-t candidate is CRC-verified before SHA-256. Per-level timing reported (time of arrival). Measured on hot_newyork (tests/run_deep_repair_tests.sh): t+1 recovered 10/10 (512B, 2KB) at L1 in 0.04-0.17 s; t+2 3/10 at L2 on 512B (4.4 s), 0/5 on 2KB; pinned-poly 600KB 9 errors in one block 2/2 at L1 (0.13 s), 9+9 in two blocks 2/2 at L3 (16.7 s). False accepts: 1,162 candidates CRC-checked, 1,024 rejected, 0 accepts. bch_test 7975/0, rs_test 6243/0, crc16_test 530/0, run_rs_tests 61/0, run_tests 149/0 in /tmp (3 pre-existing mount failures under /opt), hyper 56/0.
This commit is contained in:
1 parent
679d1a194f
commit
b27b3455c1
22 files changed
+3548
-199
No files matched your search
@@ -17,3 +17,6 @@
|
||||
/lz_rs
|
||||
/rs_test
|
||||
/testwork-rs/
|
||||
/crc16_test
|
||||
/lzply_deep_repair
|
||||
/testwork-deep/
|
||||
@@ -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
|
||||
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
|
||||
# Shared core: the v4 archive format, the per-entry pipeline
|
||||
# Shared core: the v5 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)
|
||||
@@ -108,6 +108,23 @@ lz_rs: lz_rs.o liblzrs.a liblzply.a
|
||||
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:
|
||||
@@ -128,9 +145,10 @@ rs_test: rs.c rs_test.c rs.h
|
||||
testdata:
|
||||
@if [ ! -d testdata/mixed ]; then ./tests/make_testdata.sh; fi
|
||||
|
||||
test: testdata bch_test rs_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs
|
||||
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
|
||||
./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 \
|
||||
@@ -141,16 +159,22 @@ test: testdata bch_test rs_test lzply lzply_mount lzply_stat lzply_heal lzply_ch
|
||||
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
|
||||
|
||||
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs
|
||||
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
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
|
||||
@@ -160,6 +184,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 bch_test rs_test *.o liblzply.a liblzrs.a
|
||||
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
|
||||
|
||||
.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, v4)
|
||||
compress -> BCH encode (on write, v5)
|
||||
BCH-decode -> decompress (on read)
|
||||
```
|
||||
|
||||
@@ -113,24 +113,28 @@ 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 (v4; a single format, all integers little-endian)
|
||||
## Format (v5; a single format, all integers little-endian)
|
||||
|
||||
```
|
||||
global header (16 bytes):
|
||||
magic "LZPL", version u8 (4), flags u8, entry_count u32, reserved u64
|
||||
magic "LZPL", version u8 (5), 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, u32 header_crc32,
|
||||
u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
path[path_len], data[stored_size]
|
||||
end marker: u16 path_len == 0
|
||||
```
|
||||
|
||||
`header_crc32` covers the 74 bytes before it. `blob_size` is the
|
||||
`header_crc32` covers the 76 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). Level is the lzip level (1..9) of
|
||||
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
|
||||
the blob, or 0 for a stored (uncompressed) entry. Flags: bit 0 is
|
||||
unused (it was used
|
||||
by v3), bit 1 =
|
||||
@@ -141,8 +145,10 @@ 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, and v3 archives
|
||||
are not readable (v3 had AES-256-GCM encryption, removed in v4),
|
||||
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),
|
||||
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
|
||||
@@ -171,23 +177,75 @@ polynomial `0x11D`, primitive element 2, first consecutive root 0.
|
||||
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 v4 layout plus
|
||||
`bch_poly_id` and a reserved `crc16` field before the header CRC);
|
||||
`crc16` is reserved for the follow-up CRC16 migration — writers
|
||||
write 0, readers ignore it. Full design, format, benchmarks and
|
||||
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 and `lzply` rejects `.lzrs`
|
||||
`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
|
||||
make test # BCH + RS unit tests + full archive test suites (lzply + lz_rs)
|
||||
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
|
||||
```
|
||||
|
||||
@@ -380,7 +438,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`).
|
||||
|
||||
## Limitations (v4)
|
||||
## Limitations (v5)
|
||||
|
||||
* Whole files are buffered in memory (compress, BCH, and
|
||||
the archive entry). A 50 MiB file is fine; multi-gigabyte files
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "bch.h"
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -318,15 +319,22 @@ 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). */
|
||||
/* 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. */
|
||||
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, NULL, NULL };
|
||||
static gf_tables_t gf_cache = { 0, 0, 0, 0, NULL, NULL };
|
||||
|
||||
static const gf_tables_t *gf_tables_for(int m)
|
||||
{
|
||||
@@ -335,6 +343,8 @@ 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];
|
||||
@@ -357,6 +367,8 @@ 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;
|
||||
@@ -366,6 +378,8 @@ 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;
|
||||
@@ -1005,3 +1019,789 @@ 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,4 +106,107 @@ 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,6 +398,211 @@ 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");
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/* 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
@@ -0,0 +1,658 @@
|
||||
/* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/* 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 */
|
||||
@@ -0,0 +1,213 @@
|
||||
# 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.
|
||||
+26
-9
@@ -113,16 +113,33 @@ 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 reservation (for the follow-up job)
|
||||
## CRC16 (implemented; the deep-repair oracle)
|
||||
|
||||
The `crc16` field in the entry header is RESERVED for the CRC16
|
||||
migration, which is a separate job and is NOT implemented here.
|
||||
Writers must write 0; readers must ignore the value (this reader
|
||||
accepts any value, so a future writer that fills it does not
|
||||
break this reader). The CRC16 job will define the meaning of the
|
||||
field — per-block CRC16 values, as the verification oracle for
|
||||
deeper repair levels — and the space is reserved now so the header
|
||||
layout does not move again when that job lands.
|
||||
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
|
||||
|
||||
|
||||
@@ -493,6 +493,7 @@ 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 (lzrs_write_entry_header(f, &h) != 0)
|
||||
return -1;
|
||||
@@ -506,7 +507,7 @@ static int write_entries(FILE *f, entry_list_t *list, int level,
|
||||
}
|
||||
if (lzrs_entry_encode(raw, raw_len, level, ecc, rs_level,
|
||||
&stored, &stored_len, &blob_len, &poly_id, &is_bch,
|
||||
&eff_level, h.sha) != 0) {
|
||||
&eff_level, h.sha, &h.crc16) != 0) {
|
||||
fprintf(stderr, "%s: failed to encode %s\n", lzply_progname, e->full);
|
||||
free(raw);
|
||||
return -1;
|
||||
@@ -520,7 +521,6 @@ static int write_entries(FILE *f, entry_list_t *list, int level,
|
||||
any_bch = 1;
|
||||
}
|
||||
h.rs_level = (uint8_t)rs_level;
|
||||
h.crc16 = 0; /* reserved for the CRC16 migration */
|
||||
h.orig_size = raw_len;
|
||||
h.stored_size = stored_len;
|
||||
h.blob_size = blob_len;
|
||||
@@ -1025,7 +1025,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\n", "path", "original", "stored");
|
||||
printf("%-40s %12s %12s lvl ecc crc16\n", "path", "original", "stored");
|
||||
for (;;) {
|
||||
lzrs_ehdr_t h;
|
||||
int r = lzrs_read_entry_header(f, &h);
|
||||
@@ -1054,10 +1054,10 @@ static int cmd_list(const char *archive, const char **selectors, int nselectors,
|
||||
(unsigned)h.bch_poly_id, (unsigned)h.rs_level);
|
||||
else
|
||||
snprintf(ecc, sizeof ecc, "RS r%u", (unsigned)h.rs_level);
|
||||
printf("%-40s %12s %12s %d %-8s\n", h.path,
|
||||
printf("%-40s %12s %12s %d %-8s %04x\n", h.path,
|
||||
human_size(h.orig_size, b1, sizeof b1),
|
||||
human_size(h.stored_size, b2, sizeof b2),
|
||||
h.level, ecc);
|
||||
h.level, ecc, (unsigned)h.crc16);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
@@ -1166,7 +1166,8 @@ static int cmd_extract(const char *archive, const char *dest_arg,
|
||||
int dr = lzrs_entry_decode(stored, (size_t)h.stored_size, h.level,
|
||||
is_bch, poly_id, h.rs_level,
|
||||
h.sha, (size_t)h.blob_size,
|
||||
&raw, &raw_len, &corrected_rs, &corrected_bch);
|
||||
&raw, &raw_len, &corrected_rs, &corrected_bch,
|
||||
h.crc16);
|
||||
free(stored);
|
||||
char fixmsg[96];
|
||||
fixmsg[0] = 0;
|
||||
@@ -1260,9 +1261,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\n",
|
||||
printf("%-40s %-10s %-4s %-11s %-20s %12s %12s %3s %-8s %6s\n",
|
||||
"path", "type", "perm", "symbolic", "mtime (UTC)",
|
||||
"original", "stored", "lvl", "ecc");
|
||||
"original", "stored", "lvl", "ecc", "crc16");
|
||||
for (;;) {
|
||||
lzrs_ehdr_t h;
|
||||
int r = lzrs_read_entry_header(f, &h);
|
||||
@@ -1295,13 +1296,13 @@ static int cmd_inspect(const char *archive, const char **selectors,
|
||||
(unsigned)h.bch_poly_id, (unsigned)h.rs_level);
|
||||
else
|
||||
snprintf(ecc, sizeof ecc, "RS r%u", (unsigned)h.rs_level);
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s\n",
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s %04x\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);
|
||||
ecc, (unsigned)h.crc16);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
|
||||
@@ -504,6 +504,7 @@ 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;
|
||||
@@ -517,7 +518,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) != 0) {
|
||||
&eff_level, h.sha, &h.crc16) != 0) {
|
||||
fprintf(stderr, "%s: failed to encode %s\n", lzply_progname, e->full);
|
||||
free(raw);
|
||||
return -1;
|
||||
@@ -640,7 +641,7 @@ static int cmd_create(const char **inputs, int ninputs, const char *output_arg,
|
||||
rc = EXIT_IO;
|
||||
goto done;
|
||||
}
|
||||
/* The format is v4, always. */
|
||||
/* The format is v5, always. */
|
||||
f = fopen(out_path, "wb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot create %s: %s\n", lzply_progname, out_path,
|
||||
@@ -782,7 +783,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 v4, always */
|
||||
(void)old_version; /* the format is v5, always */
|
||||
new_count = (uint32_t)(old.len - nrep + list.len);
|
||||
if (!has_dup) {
|
||||
/* True incremental append: stage the new entries to a temp
|
||||
@@ -1011,11 +1012,25 @@ static int open_archive(const char *path, FILE **f_out, uint32_t *count_out,
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
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;
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
*f_out = f;
|
||||
*size_out = st.st_size;
|
||||
@@ -1035,7 +1050,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\n", "path", "original", "stored");
|
||||
printf("%-40s %12s %12s lvl ecc crc16\n", "path", "original", "stored");
|
||||
for (;;) {
|
||||
ehdr_t h;
|
||||
int r = read_entry_header(f, &h);
|
||||
@@ -1064,10 +1079,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\n", h.path,
|
||||
printf("%-40s %12s %12s %d %-8s %04x\n", h.path,
|
||||
human_size(h.orig_size, b1, sizeof b1),
|
||||
human_size(h.stored_size, b2, sizeof b2),
|
||||
h.level, ecc);
|
||||
h.level, ecc, (unsigned)h.crc16);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
@@ -1177,7 +1192,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);
|
||||
&raw, &raw_len, &corrected, h.crc16);
|
||||
free(stored);
|
||||
if (dr != 0) {
|
||||
fprintf(stderr, "%s: %s: corrupt or unrecoverable data\n",
|
||||
@@ -1263,9 +1278,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\n",
|
||||
printf("%-40s %-10s %-4s %-11s %-20s %12s %12s %3s %-8s %6s\n",
|
||||
"path", "type", "perm", "symbolic", "mtime (UTC)",
|
||||
"original", "stored", "lvl", "ecc");
|
||||
"original", "stored", "lvl", "ecc", "crc16");
|
||||
for (;;) {
|
||||
ehdr_t h;
|
||||
int r = read_entry_header(f, &h);
|
||||
@@ -1298,13 +1313,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\n",
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s %04x\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);
|
||||
ecc, (unsigned)h.crc16);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
/* 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;
|
||||
}
|
||||
}
|
||||
+168
-51
@@ -8,19 +8,20 @@
|
||||
* format. (v3 archives are rejected outright; the format changed
|
||||
* in v4.)
|
||||
*
|
||||
* Archive format v4 (all integers little-endian):
|
||||
* Archive format v5 (all integers little-endian):
|
||||
* global header (16 bytes):
|
||||
* magic "LZPL", version u8 (=4), flags u8, entry_count u32,
|
||||
* magic "LZPL", version u8 (=5), 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, u32 header_crc32,
|
||||
* u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 74 bytes before it; blob_size is the
|
||||
* (header_crc32 covers the 76 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)
|
||||
* seconds since the epoch, UTC; crc16 is CRC-16/CCITT-FALSE of
|
||||
* the blob)
|
||||
* end marker: u16 path_len == 0
|
||||
* Flags: bit 0 is unused (it was used by v3), bit 1 =
|
||||
* directory, bit 2 = BCH mode.
|
||||
@@ -163,6 +164,39 @@ 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). */
|
||||
@@ -331,7 +365,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])
|
||||
uint8_t sha_out[32], uint16_t *crc16_out)
|
||||
{
|
||||
uint8_t *comp = NULL, *blob = NULL, *ecout = NULL;
|
||||
size_t comp_len = 0, blob_len = 0, ec_len = 0;
|
||||
@@ -377,6 +411,12 @@ 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);
|
||||
@@ -428,35 +468,72 @@ 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,
|
||||
* 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 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).
|
||||
*
|
||||
* Two-pass silent repair (BCH entries only):
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/* 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)
|
||||
uint8_t **raw, size_t *raw_len, int *corrected,
|
||||
uint16_t want_crc16)
|
||||
{
|
||||
*corrected = 0;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (!is_bch) {
|
||||
/* No error correction: the stored data is the blob itself. */
|
||||
/* No error correction: the stored data is the blob itself.
|
||||
* CRC-check it before decompressing anything. */
|
||||
uint16_t got;
|
||||
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);
|
||||
@@ -471,22 +548,32 @@ 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;
|
||||
/* Pass 1: standard BCH decode, then decompress + hash. */
|
||||
/* 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. */
|
||||
if (bch_decode(stored, stored_len, blob_size, poly, blob, &corr) == 0) {
|
||||
*corrected = corr;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
/* Pass-1 blob failed decompress/hash: fall through to pass 2. */
|
||||
/* Pass-1 blob failed CRC / decompress / hash: fall through
|
||||
* to pass 2. */
|
||||
}
|
||||
/* Pass 2: try alternative BCH decodings; accept the first whose
|
||||
* decompressed output hashes correctly. */
|
||||
/* Pass 2: try alternative BCH decodings; CRC-check each candidate
|
||||
* first (cheap) and 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);
|
||||
@@ -497,10 +584,15 @@ 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 = blob_to_raw_checked(cands + (size_t)i * candsize,
|
||||
blob_size, level,
|
||||
want_sha, &out_len);
|
||||
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);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
@@ -512,6 +604,8 @@ 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;
|
||||
}
|
||||
|
||||
@@ -532,7 +626,8 @@ 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. */
|
||||
* no error correction both are 0. crc16 is CRC-16/CCITT-FALSE of the
|
||||
* blob (0xFFFF for a directory entry, whose blob is empty). */
|
||||
|
||||
int write_entry_header(FILE *f, const ehdr_t *h){
|
||||
uint8_t buf[LZPLY_EHDR_SIZE];
|
||||
@@ -551,7 +646,8 @@ 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);
|
||||
put32le(buf + 74, crc32_of(buf, 74));
|
||||
put16le(buf + 74, h->crc16);
|
||||
put32le(buf + 76, crc32_of(buf, 76));
|
||||
if (fwrite(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (plen > 0 && fwrite(h->path, 1, plen, f) != plen)
|
||||
@@ -572,10 +668,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 + 74);
|
||||
put32le(buf + 74, 0);
|
||||
got_crc = crc32_of(buf, 74);
|
||||
put32le(buf + 74, want_crc);
|
||||
want_crc = get32le(buf + 76);
|
||||
put32le(buf + 76, 0);
|
||||
got_crc = crc32_of(buf, 76);
|
||||
put32le(buf + 76, want_crc);
|
||||
if (got_crc != want_crc)
|
||||
return -1;
|
||||
h->level = buf[2];
|
||||
@@ -588,6 +684,7 @@ 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) {
|
||||
@@ -619,8 +716,10 @@ 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 || buf[4] != LZPLY_VERSION)
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0)
|
||||
return -1;
|
||||
if (buf[4] != LZPLY_VERSION)
|
||||
return -2; /* right magic, wrong version (e.g. v4) */
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
@@ -796,15 +895,20 @@ 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. */
|
||||
* 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. */
|
||||
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 || buf[4] != LZPLY_VERSION)
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0)
|
||||
return -1;
|
||||
*version_out = buf[4];
|
||||
if (buf[4] != LZPLY_VERSION)
|
||||
return -2;
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
@@ -832,11 +936,24 @@ int scan_archive(const char *path, int *version_out, uint
|
||||
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;
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
memset(entries, 0, sizeof *entries);
|
||||
for (;;) {
|
||||
|
||||
+66
-27
@@ -1,26 +1,28 @@
|
||||
/* lzply_lib.h - shared core of the lzply archiver and lzply_mount.
|
||||
*
|
||||
* Everything both programs need: the v4 archive format, the per-entry
|
||||
* Everything both programs need: the v5 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: v4 is the only
|
||||
* format. (v3 archives are rejected outright; the format changed
|
||||
* in v4.)
|
||||
* 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.)
|
||||
*
|
||||
* Archive format v4 (all integers little-endian):
|
||||
* Archive format v5 (all integers little-endian):
|
||||
* global header (16 bytes):
|
||||
* magic "LZPL", version u8 (=4), flags u8, entry_count u32,
|
||||
* magic "LZPL", version u8 (=5), 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, u32 header_crc32,
|
||||
* u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 74 bytes before it; blob_size is the
|
||||
* (header_crc32 covers the 76 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)
|
||||
* seconds since the epoch, UTC; 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: when the compressed blob would be no smaller
|
||||
@@ -30,6 +32,21 @@
|
||||
* 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
|
||||
@@ -42,9 +59,9 @@
|
||||
#include "sha256.h"
|
||||
|
||||
#define LZPLY_MAGIC "LZPL"
|
||||
#define LZPLY_VERSION 4 /* the only format version */
|
||||
#define LZPLY_VERSION 5 /* the only format version */
|
||||
#define LZPLY_HDR_SIZE 16
|
||||
#define LZPLY_EHDR_SIZE 78
|
||||
#define LZPLY_EHDR_SIZE 80
|
||||
#define LZPLY_END_MARKER 0
|
||||
|
||||
#define FLAG_ISDIR 0x02
|
||||
@@ -90,6 +107,13 @@ 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);
|
||||
@@ -115,30 +139,39 @@ typedef struct {
|
||||
} ecc_opt_t;
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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]);
|
||||
uint8_t sha_out[32], uint16_t *crc16_out);
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
|
||||
* 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 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). */
|
||||
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);
|
||||
uint8_t **raw, size_t *raw_len, int *corrected,
|
||||
uint16_t want_crc16);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Archive header I/O */
|
||||
@@ -151,10 +184,12 @@ 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. */
|
||||
* no error correction both are 0. crc16 covers the blob (see above);
|
||||
* for a directory entry (empty blob) it is 0xFFFF. */
|
||||
|
||||
int write_entry_header(FILE *f, const ehdr_t *h);
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
@@ -162,7 +197,11 @@ 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. */
|
||||
* 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. */
|
||||
int read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out);
|
||||
|
||||
@@ -213,8 +252,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 78-byte header), and its total on-disk length
|
||||
* (78 + path_len + stored_size). */
|
||||
* offset (start of the 80-byte header), and its total on-disk length
|
||||
* (80 + path_len + stored_size). */
|
||||
typedef struct {
|
||||
char *path;
|
||||
off_t offset;
|
||||
|
||||
+4
-2
@@ -411,7 +411,8 @@ 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);
|
||||
(size_t)n->hdr.blob_size, &raw, &raw_len, &corrected,
|
||||
n->hdr.crc16);
|
||||
free(stored);
|
||||
if (rc != 0)
|
||||
return -EIO; /* corrupt: BCH uncorrectable / SHA mismatch */
|
||||
@@ -538,6 +539,7 @@ 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) {
|
||||
@@ -580,7 +582,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) != 0)
|
||||
&is_bch, &eff_level, h.sha, &h.crc16) != 0)
|
||||
goto fail;
|
||||
h.level = (uint8_t)eff_level; /* 0 when stored uncompressed */
|
||||
}
|
||||
|
||||
+16
-14
@@ -10,11 +10,11 @@
|
||||
* 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 v4 78-byte
|
||||
* layout plus bch_poly_id and a reserved crc16 field 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.
|
||||
* 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
|
||||
@@ -43,7 +43,7 @@ int lzrs_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])
|
||||
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;
|
||||
@@ -53,7 +53,7 @@ int lzrs_entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
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) != 0)
|
||||
is_bch_out, level_out, sha_out, crc16_out) != 0)
|
||||
return -1;
|
||||
if (parity == 0) {
|
||||
*stored = bch_stored;
|
||||
@@ -86,7 +86,8 @@ 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)
|
||||
int *corrected_rs, int *corrected_bch,
|
||||
uint16_t want_crc16)
|
||||
{
|
||||
const bch_poly_t *poly = NULL;
|
||||
size_t bch_len;
|
||||
@@ -111,7 +112,7 @@ int lzrs_entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
return -1;
|
||||
rc = entry_decode(stored, stored_len, level,
|
||||
is_bch, poly_id, want_sha, blob_size,
|
||||
raw, raw_len, &corr_bch);
|
||||
raw, raw_len, &corr_bch, want_crc16);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
*corrected_bch = corr_bch;
|
||||
@@ -128,7 +129,7 @@ int lzrs_entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
}
|
||||
rc = entry_decode(bch_stored, bch_len, level,
|
||||
is_bch, poly_id, want_sha, blob_size,
|
||||
raw, raw_len, &corr_bch);
|
||||
raw, raw_len, &corr_bch, want_crc16);
|
||||
free(bch_stored);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
@@ -143,8 +144,8 @@ int lzrs_entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
* 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).
|
||||
* The crc16 field is reserved for the follow-up CRC16 migration:
|
||||
* writers write 0, readers ignore 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)
|
||||
{
|
||||
@@ -216,8 +217,9 @@ int lzrs_read_entry_header(FILE *f, lzrs_ehdr_t *h)
|
||||
} else if (h->bch_poly_id != 0) {
|
||||
return -1;
|
||||
}
|
||||
/* crc16 is reserved: any value is accepted for now, so a
|
||||
* future writer that fills it does not break this reader. */
|
||||
/* 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);
|
||||
|
||||
+32
-21
@@ -23,18 +23,25 @@
|
||||
* (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)
|
||||
* 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 v4. Flags: bit 1 =
|
||||
* directory, bit 2 = BCH mode (same bits as v4).
|
||||
* (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 RESERVED for the follow-up CRC16 migration: writers
|
||||
* must write 0, readers must ignore it. The CRC16 job will define
|
||||
* its meaning (per-block CRC16 table); this field reserves the
|
||||
* space in the header so the layout does not move again.
|
||||
* 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
|
||||
@@ -53,8 +60,8 @@
|
||||
#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 reserved
|
||||
* (must be 0 on write, ignored on read). */
|
||||
* 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;
|
||||
@@ -63,7 +70,7 @@ typedef struct {
|
||||
uint32_t mode;
|
||||
uint64_t mtime;
|
||||
uint16_t bch_poly_id;
|
||||
uint16_t crc16; /* reserved, see above */
|
||||
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);
|
||||
@@ -77,29 +84,33 @@ 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. *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. */
|
||||
* 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]);
|
||||
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, 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. */
|
||||
* 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);
|
||||
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
|
||||
|
||||
Executable
+417
@@ -0,0 +1,417 @@
|
||||
#!/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 ]
|
||||
+25
-2
@@ -138,9 +138,9 @@ cmp -s "$TD/mixed/source.c" "$WORK/app-out/source.c" &&
|
||||
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") - 102 - 2))
|
||||
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=102 count="$LSZ" of="$WORK/lp.bin" 2>/dev/null
|
||||
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"
|
||||
@@ -280,6 +280,29 @@ 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"
|
||||
|
||||
+36
-24
@@ -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) + 78 (entry header) + 8 ("text.txt") = 102,
|
||||
# archive layout: 16 (global) + 80 (entry header) + 8 ("text.txt") = 104,
|
||||
# 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=102 count=$((ASZ - 104)) status=none > "$WORK/text6.lzip" 2>/dev/null
|
||||
dd if="$WORK/text6.lzply" bs=1 skip=104 count=$((ASZ - 106)) 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 102 (16 + 78 + 8 for "text.txt"). All
|
||||
# Stored data starts at offset 104 (16 + 80 + 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 ([102,118)).
|
||||
# bytes, so its first block is only 16 stored bytes ([104,120)).
|
||||
# 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 118" "0018 2 0" "0025 4 0" "003a 32 0"; do
|
||||
for SPEC in "0002 2 120" "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 118" "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" 102 "$END" >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/bch-${POLY}a.lzply" 42 "$T" 104 "$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 118" "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)) 102 "$END" >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/bch-${POLY}b.lzply" 43 $((T + 1)) 104 "$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 102 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/combo-c.lzply" 46 16 104 $((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,6 +139,15 @@ 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
|
||||
@@ -261,17 +270,20 @@ 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): 4 for the v4 format, with or
|
||||
# format version byte (offset 4): 5 for the v5 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" = "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)"
|
||||
[ "$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"
|
||||
|
||||
# --- 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 102, well inside block 1) and verify recovery / failure.
|
||||
# (offset 105, 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"
|
||||
@@ -279,14 +291,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 102 1102 >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/split-a.lzply" 51 8 105 1105 >/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 102 1102 >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/split-b.lzply" 52 9 105 1105 >/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"
|
||||
@@ -485,13 +497,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 102 for an 8-char path) and -i still succeeds while
|
||||
# (data starts at 104 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 102 are well inside it.
|
||||
# ~1 KiB and 100 zeroed bytes at 104 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=102 count=100 conv=notrunc status=none
|
||||
dd if=/dev/zero of="$WORK/rand-corrupt.lzply" bs=1 seek=104 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)"
|
||||
@@ -738,14 +750,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 102 (16 + 78 + 8 for "tiny.txt"); flip 5 bits in the
|
||||
# Data starts at 104 (16 + 80 + 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 102 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/heal-bits-a.lzply" 61 5 104 $((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" &&
|
||||
@@ -755,7 +767,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 102 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/heal-bits-b.lzply" 62 9 104 $((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
|
||||
@@ -802,7 +814,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 102 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/check-err5.lzply" 61 5 104 $((SZ - 2)) >/dev/null
|
||||
"$CHECK" --json "$WORK/check-err5.lzply" 2>/dev/null | python3 -c '
|
||||
import json, sys
|
||||
d = json.load(sys.stdin)
|
||||
@@ -819,7 +831,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 102 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/check-err9.lzply" 62 9 104 $((SZ - 2)) >/dev/null
|
||||
OUT=$("$CHECK" "$WORK/check-err9.lzply" 2>&1)
|
||||
RC=$?
|
||||
[ "$RC" = "3" ] && echo "$OUT" | grep -q "uncorrectable" &&
|
||||
@@ -1080,12 +1092,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 104: 16 + 78 + 10 for "random.bin"); -t still
|
||||
# entry (data starts at 106: 16 + 80 + 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 104 $((SZ - 2)) >/dev/null
|
||||
"$CORRUPT_BITS" "$WORK/store-rand-c.lzply" 55 1 106 $((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