amanecer-native 0.2.0a0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,241 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "amanecer-native"
7
+ version = "0.2.0-alpha.0"
8
+ dependencies = [
9
+ "crc32c",
10
+ "crc32fast",
11
+ "libz-sys",
12
+ "lz4_flex",
13
+ "memchr",
14
+ "pyo3",
15
+ "snap",
16
+ ]
17
+
18
+ [[package]]
19
+ name = "cc"
20
+ version = "1.12.0"
21
+ source = "registry+https://github.com/rust-lang/crates.io-index"
22
+ checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"
23
+ dependencies = [
24
+ "find-msvc-tools",
25
+ "shlex",
26
+ ]
27
+
28
+ [[package]]
29
+ name = "cfg-if"
30
+ version = "1.0.5"
31
+ source = "registry+https://github.com/rust-lang/crates.io-index"
32
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
33
+
34
+ [[package]]
35
+ name = "crc32c"
36
+ version = "0.6.9"
37
+ source = "registry+https://github.com/rust-lang/crates.io-index"
38
+ checksum = "7f132a176423ee852e8f0a35d43088d1850966b50745be818a88b76f64b1c6cb"
39
+ dependencies = [
40
+ "rustc_version",
41
+ ]
42
+
43
+ [[package]]
44
+ name = "crc32fast"
45
+ version = "1.5.6"
46
+ source = "registry+https://github.com/rust-lang/crates.io-index"
47
+ checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
48
+ dependencies = [
49
+ "cfg-if",
50
+ ]
51
+
52
+ [[package]]
53
+ name = "find-msvc-tools"
54
+ version = "0.1.16"
55
+ source = "registry+https://github.com/rust-lang/crates.io-index"
56
+ checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
57
+
58
+ [[package]]
59
+ name = "heck"
60
+ version = "0.5.0"
61
+ source = "registry+https://github.com/rust-lang/crates.io-index"
62
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
63
+
64
+ [[package]]
65
+ name = "libc"
66
+ version = "0.2.191"
67
+ source = "registry+https://github.com/rust-lang/crates.io-index"
68
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
69
+
70
+ [[package]]
71
+ name = "libz-sys"
72
+ version = "1.1.33"
73
+ source = "registry+https://github.com/rust-lang/crates.io-index"
74
+ checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045"
75
+ dependencies = [
76
+ "cc",
77
+ "libc",
78
+ "pkg-config",
79
+ "vcpkg",
80
+ ]
81
+
82
+ [[package]]
83
+ name = "lz4_flex"
84
+ version = "0.11.7"
85
+ source = "registry+https://github.com/rust-lang/crates.io-index"
86
+ checksum = "13591d77a9b6d941f7e6fcade7f9dfd9e801308752bde50c0a9bb5852778c22c"
87
+
88
+ [[package]]
89
+ name = "memchr"
90
+ version = "2.8.3"
91
+ source = "registry+https://github.com/rust-lang/crates.io-index"
92
+ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
93
+
94
+ [[package]]
95
+ name = "once_cell"
96
+ version = "1.21.4"
97
+ source = "registry+https://github.com/rust-lang/crates.io-index"
98
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
99
+
100
+ [[package]]
101
+ name = "pkg-config"
102
+ version = "0.3.34"
103
+ source = "registry+https://github.com/rust-lang/crates.io-index"
104
+ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
105
+
106
+ [[package]]
107
+ name = "portable-atomic"
108
+ version = "1.15.0"
109
+ source = "registry+https://github.com/rust-lang/crates.io-index"
110
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
111
+
112
+ [[package]]
113
+ name = "proc-macro2"
114
+ version = "1.0.107"
115
+ source = "registry+https://github.com/rust-lang/crates.io-index"
116
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
117
+ dependencies = [
118
+ "unicode-ident",
119
+ ]
120
+
121
+ [[package]]
122
+ name = "pyo3"
123
+ version = "0.29.3"
124
+ source = "registry+https://github.com/rust-lang/crates.io-index"
125
+ checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655"
126
+ dependencies = [
127
+ "libc",
128
+ "once_cell",
129
+ "portable-atomic",
130
+ "pyo3-build-config",
131
+ "pyo3-ffi",
132
+ "pyo3-macros",
133
+ ]
134
+
135
+ [[package]]
136
+ name = "pyo3-build-config"
137
+ version = "0.29.3"
138
+ source = "registry+https://github.com/rust-lang/crates.io-index"
139
+ checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb"
140
+ dependencies = [
141
+ "target-lexicon",
142
+ ]
143
+
144
+ [[package]]
145
+ name = "pyo3-ffi"
146
+ version = "0.29.3"
147
+ source = "registry+https://github.com/rust-lang/crates.io-index"
148
+ checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330"
149
+ dependencies = [
150
+ "libc",
151
+ "pyo3-build-config",
152
+ ]
153
+
154
+ [[package]]
155
+ name = "pyo3-macros"
156
+ version = "0.29.3"
157
+ source = "registry+https://github.com/rust-lang/crates.io-index"
158
+ checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6"
159
+ dependencies = [
160
+ "proc-macro2",
161
+ "pyo3-macros-backend",
162
+ "quote",
163
+ "syn",
164
+ ]
165
+
166
+ [[package]]
167
+ name = "pyo3-macros-backend"
168
+ version = "0.29.3"
169
+ source = "registry+https://github.com/rust-lang/crates.io-index"
170
+ checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3"
171
+ dependencies = [
172
+ "heck",
173
+ "proc-macro2",
174
+ "quote",
175
+ "syn",
176
+ ]
177
+
178
+ [[package]]
179
+ name = "quote"
180
+ version = "1.0.47"
181
+ source = "registry+https://github.com/rust-lang/crates.io-index"
182
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
183
+ dependencies = [
184
+ "proc-macro2",
185
+ ]
186
+
187
+ [[package]]
188
+ name = "rustc_version"
189
+ version = "0.4.1"
190
+ source = "registry+https://github.com/rust-lang/crates.io-index"
191
+ checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
192
+ dependencies = [
193
+ "semver",
194
+ ]
195
+
196
+ [[package]]
197
+ name = "semver"
198
+ version = "1.0.28"
199
+ source = "registry+https://github.com/rust-lang/crates.io-index"
200
+ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
201
+
202
+ [[package]]
203
+ name = "shlex"
204
+ version = "2.0.1"
205
+ source = "registry+https://github.com/rust-lang/crates.io-index"
206
+ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
207
+
208
+ [[package]]
209
+ name = "snap"
210
+ version = "1.1.2"
211
+ source = "registry+https://github.com/rust-lang/crates.io-index"
212
+ checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
213
+
214
+ [[package]]
215
+ name = "syn"
216
+ version = "2.0.119"
217
+ source = "registry+https://github.com/rust-lang/crates.io-index"
218
+ checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
219
+ dependencies = [
220
+ "proc-macro2",
221
+ "quote",
222
+ "unicode-ident",
223
+ ]
224
+
225
+ [[package]]
226
+ name = "target-lexicon"
227
+ version = "0.13.6"
228
+ source = "registry+https://github.com/rust-lang/crates.io-index"
229
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
230
+
231
+ [[package]]
232
+ name = "unicode-ident"
233
+ version = "1.0.27"
234
+ source = "registry+https://github.com/rust-lang/crates.io-index"
235
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
236
+
237
+ [[package]]
238
+ name = "vcpkg"
239
+ version = "0.2.15"
240
+ source = "registry+https://github.com/rust-lang/crates.io-index"
241
+ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
@@ -0,0 +1,31 @@
1
+ [package]
2
+ name = "amanecer-native"
3
+ version = "0.2.0-alpha.0"
4
+ edition = "2021"
5
+ license = "GPL-3.0-or-later"
6
+ description = "Optional compiled scan kernels for amanecer (amanecer._native)"
7
+ publish = false
8
+ readme = "README.md"
9
+
10
+ [lib]
11
+ name = "amanecer_native"
12
+ crate-type = ["cdylib", "rlib"]
13
+
14
+ [features]
15
+ default = []
16
+ # the Python bindings; maturin enables this (pyproject.toml). The fuzz targets build without it.
17
+ python = ["dep:pyo3"]
18
+ salvage-zlib = ["dep:libz-sys"]
19
+
20
+ [dependencies]
21
+ pyo3 = { version = "0.29", features = ["extension-module"], optional = true }
22
+ crc32c = "0.6"
23
+ crc32fast = "1.4"
24
+ snap = "1"
25
+ memchr = "2"
26
+ lz4_flex = { version = "0.11", default-features = false, features = ["safe-encode", "safe-decode", "std"] }
27
+ libz-sys = { version = "1", optional = true }
28
+
29
+ [profile.release]
30
+ lto = true
31
+ codegen-units = 1
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: amanecer-native
3
+ Version: 0.2.0a0
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Classifier: Topic :: System :: Recovery Tools
7
+ Summary: Optional compiled kernels for amanecer: installs the amanecer_native module
8
+ License-Expression: GPL-3.0-or-later
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
11
+
12
+ # amanecer-native
13
+
14
+ Optional compiled kernels for amanecer: installs the `amanecer_native` module (CRC-32C, PST/OST
15
+ trailer scan, signature search, VHDX BAT scoring, entropy window tests, Snappy/LZ4 block
16
+ decoding). amanecer gives identical results without it. Install with `pip install ./native` from
17
+ a checkout (needs a Rust toolchain), or from a built wheel. Set `AMANECER_NATIVE=0` to force the
18
+ pure-Python kernels.
19
+
@@ -0,0 +1,7 @@
1
+ # amanecer-native
2
+
3
+ Optional compiled kernels for amanecer: installs the `amanecer_native` module (CRC-32C, PST/OST
4
+ trailer scan, signature search, VHDX BAT scoring, entropy window tests, Snappy/LZ4 block
5
+ decoding). amanecer gives identical results without it. Install with `pip install ./native` from
6
+ a checkout (needs a Rust toolchain), or from a built wheel. Set `AMANECER_NATIVE=0` to force the
7
+ pure-Python kernels.
@@ -0,0 +1,34 @@
1
+ # Third-party crates in amanecer-native
2
+
3
+ The optional extension (`native/`, GPL-3.0-or-later) links these crates from crates.io. All licences are
4
+ compatible with GPL-3.0-or-later; where a crate is dual-licensed, it is used under its permissive
5
+ (MIT or Apache-2.0) option. The pure-Python package uses none of them.
6
+
7
+ Linked into the extension:
8
+
9
+ | Crate | Version | Licence | Used for |
10
+ |---|---|---|---|
11
+ | crc32c | 0.6.9 | MIT OR Apache-2.0 | CRC-32C (SSE4.2 / ARMv8 CRC instructions where present) |
12
+ | crc32fast | 1.5.6 | MIT OR Apache-2.0 | the MS-PST CRC-32 (SIMD / PCLMULQDQ where present) |
13
+ | memchr | 2.8.3 | Unlicense OR MIT | SIMD substring search (`memmem`) |
14
+ | snap | 1.1.2 | BSD-3-Clause | Snappy raw-format blocks (AFF4) |
15
+ | lz4_flex | 0.11.7 | MIT | LZ4 block format (AFF4), safe-decode mode |
16
+ | pyo3, pyo3-ffi, pyo3-macros, pyo3-macros-backend, pyo3-build-config | 0.29.3 | MIT OR Apache-2.0 | the Python bindings |
17
+ | libc | 0.2.191 | MIT OR Apache-2.0 | (pyo3) |
18
+ | cfg-if, once_cell, portable-atomic | various | MIT OR Apache-2.0 / MIT | (pyo3 and its macros) |
19
+ | libz-sys | 1.1.33 | MIT OR Apache-2.0 | zlib bindings; only with the `salvage-zlib` feature, which the wheel does not enable |
20
+
21
+ Build-time only (proc macros and build scripts, not shipped in the wheel): proc-macro2, quote,
22
+ syn, heck, rustc_version, semver (MIT OR Apache-2.0), unicode-ident
23
+ ((MIT OR Apache-2.0) AND Unicode-3.0), target-lexicon (Apache-2.0 WITH LLVM-exception); with the
24
+ `salvage-zlib` feature also cc, pkg-config, vcpkg, find-msvc-tools and shlex (MIT OR Apache-2.0).
25
+
26
+ Fuzzing only (`native/fuzz/`, never shipped): libfuzzer-sys (MIT OR Apache-2.0, bundles LLVM's
27
+ libFuzzer under Apache-2.0 WITH LLVM-exception).
28
+
29
+ Considered and not used: `ntfs` (Colin Finck, MIT OR Apache-2.0) and `mft`/`evtx` (omerbenamram,
30
+ MIT OR Apache-2.0) are good parsers of intact NTFS volumes, but amanecer's NTFS code works on
31
+ partial, damaged volumes and on single records out of context (anchors, verdicts per file), and the
32
+ profile showed no NTFS hot spot worth a second implementation. zlib-rs / flate2 were not adopted:
33
+ every zlib use in the Python package goes through CPython's zlib module, which is already C, and the
34
+ ciphertext test depends on deflate's exact output size, which only the same zlib reproduces.
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.5,<2"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "amanecer-native"
7
+ version = "0.2.0a0"
8
+ description = "Optional compiled kernels for amanecer: installs the amanecer_native module"
9
+ license = "GPL-3.0-or-later"
10
+ requires-python = ">=3.10"
11
+ readme = "README.md"
12
+ classifiers = ["Programming Language :: Rust", "Programming Language :: Python :: Implementation :: CPython", "Topic :: System :: Recovery Tools"]
13
+
14
+ [tool.maturin]
15
+ module-name = "amanecer_native"
16
+ features = ["python"]
@@ -0,0 +1,410 @@
1
+ //! The kernels themselves, free of Python so the fuzz targets can call them directly.
2
+ //! Each one mirrors a pure-Python function in the `amanecer` package exactly; the Python tests
3
+ //! (tests/test_native.py) compare the two on random and adversarial inputs.
4
+
5
+ /// CRC-32C, chainable like `amanecer.core.crc.crc32c(data, crc)`.
6
+ pub fn crc32c(data: &[u8], crc: u32) -> u32 {
7
+ crc32c::crc32c_append(crc, data)
8
+ }
9
+
10
+ /// MS-PST CRC-32: zlib.crc32(b, 0xFFFFFFFF) ^ 0xFFFFFFFF.
11
+ pub fn pst_crc(data: &[u8]) -> u32 {
12
+ let mut h = crc32fast::Hasher::new_with_initial(0xFFFF_FFFF);
13
+ h.update(data);
14
+ h.finalize() ^ 0xFFFF_FFFF
15
+ }
16
+
17
+ #[inline]
18
+ fn pst_sig(ib: u64, bid: u64) -> u16 {
19
+ let x = ib ^ bid;
20
+ (((x >> 16) ^ x) & 0xFFFF) as u16
21
+ }
22
+
23
+ #[derive(Clone, Copy, Debug)]
24
+ pub struct PstLayout {
25
+ pub page: usize,
26
+ pub trailer: usize,
27
+ pub align: usize,
28
+ pub block_trailer: usize,
29
+ pub max_cb: usize,
30
+ }
31
+
32
+ #[derive(Default, Debug)]
33
+ pub struct PstScan {
34
+ /// page offsets whose trailer ptype pair looks like a page (the caller verifies them)
35
+ pub pages: Vec<u64>,
36
+ /// (start, cb, bid) of data blocks whose signature and CRC check out, in file order
37
+ pub blocks: Vec<(u64, u32, u64)>,
38
+ pub bad_crc: u64,
39
+ }
40
+
41
+ /// The pure-Python loop of `amanecer.mail.pst.rebuild.scan` without numpy: page candidates at
42
+ /// every page boundary, data-block trailers at every `align` boundary.
43
+ pub fn pst_scan(mm: &[u8], l: &PstLayout) -> PstScan {
44
+ pst_scan_window(mm, l, 0, 0)
45
+ }
46
+
47
+ /// Scan an aligned window with a prefix from the previous window. Page starts
48
+ /// and block ends in the overlap were checked by the previous window.
49
+ pub fn pst_scan_window(mm: &[u8], l: &PstLayout, base: u64, skip: usize) -> PstScan {
50
+ let mut r = PstScan::default();
51
+ let size = mm.len();
52
+ if l.page == 0
53
+ || l.align == 0
54
+ || l.block_trailer < 16
55
+ || l.trailer >= l.page - 1
56
+ || l.block_trailer > l.align
57
+ || skip > size
58
+ || skip % l.page != 0
59
+ || skip % l.align != 0
60
+ || base.checked_add(size as u64).is_none()
61
+ {
62
+ return r;
63
+ }
64
+ if size >= l.page {
65
+ let mut ib = skip;
66
+ while ib + l.page <= size {
67
+ let t = ib + l.trailer;
68
+ let p = mm[t];
69
+ if p == mm[t + 1] && (0x80..=0x86).contains(&p) {
70
+ r.pages.push(base + ib as u64);
71
+ }
72
+ ib += l.page;
73
+ }
74
+ }
75
+ let mut end = skip.saturating_add(l.align);
76
+ while end <= size {
77
+ let t = &mm[end - l.block_trailer..end - l.block_trailer + 16];
78
+ let cb = u16::from_le_bytes([t[0], t[1]]) as usize;
79
+ let ws = u16::from_le_bytes([t[2], t[3]]);
80
+ let dcrc = u32::from_le_bytes([t[4], t[5], t[6], t[7]]);
81
+ let b = u64::from_le_bytes([t[8], t[9], t[10], t[11], t[12], t[13], t[14], t[15]]);
82
+ if cb > 0 && cb <= l.max_cb && b != 0 {
83
+ let tot = (cb + l.block_trailer + l.align - 1) / l.align * l.align;
84
+ if tot <= end {
85
+ let s = end - tot;
86
+ if pst_sig(base + s as u64, b) == ws {
87
+ if pst_crc(&mm[s..s + cb]) == dcrc {
88
+ r.blocks.push((base + s as u64, cb as u32, b));
89
+ } else {
90
+ r.bad_crc += 1;
91
+ }
92
+ }
93
+ }
94
+ }
95
+ end += l.align;
96
+ }
97
+ r
98
+ }
99
+
100
+ #[inline]
101
+ fn is_text_byte(c: u8) -> bool {
102
+ c == 9 || c == 10 || c == 13 || (32..127).contains(&c)
103
+ }
104
+
105
+ #[inline]
106
+ fn is_cont(c: u8) -> bool {
107
+ (0x80..=0xBF).contains(&c)
108
+ }
109
+
110
+ /// Per `gran`-byte window of `data`, `amanecer.salvage.regions._text_at`: 1 text, 0 not text,
111
+ /// 2 undecided (valid UTF-8 with non-ASCII characters, whose printability the caller checks
112
+ /// with Python's own Unicode tables).
113
+ pub fn text_flags(data: &[u8], gran: usize) -> Vec<u8> {
114
+ let n = data.len();
115
+ if gran == 0 {
116
+ return Vec::new();
117
+ }
118
+ let mut out = Vec::with_capacity(n / gran + 1);
119
+ let mut i = 0usize;
120
+ while i < n {
121
+ let we = (i + gran).min(n);
122
+ if data[i..we].iter().all(|&c| is_text_byte(c)) {
123
+ out.push(1);
124
+ i += gran;
125
+ continue;
126
+ }
127
+ let mut lo = i;
128
+ let floor = i.saturating_sub(3);
129
+ while lo > floor && is_cont(data[lo]) {
130
+ lo -= 1;
131
+ }
132
+ if is_cont(data[lo]) {
133
+ out.push(0);
134
+ i += gran;
135
+ continue;
136
+ }
137
+ let mut hi = we;
138
+ let cap = (i + gran + 3).min(n);
139
+ while hi < cap && is_cont(data[hi]) {
140
+ hi += 1;
141
+ }
142
+ let v = match std::str::from_utf8(&data[lo..hi]) {
143
+ Err(_) => 0,
144
+ Ok(s) => {
145
+ let mut nonascii = false;
146
+ let mut bad = false;
147
+ for ch in s.chars() {
148
+ let c = ch as u32;
149
+ if c < 0x80 {
150
+ if !is_text_byte(c as u8) {
151
+ bad = true;
152
+ break;
153
+ }
154
+ } else {
155
+ nonascii = true;
156
+ }
157
+ }
158
+ if bad {
159
+ 0
160
+ } else if nonascii {
161
+ 2
162
+ } else {
163
+ 1
164
+ }
165
+ }
166
+ };
167
+ out.push(v);
168
+ i += gran;
169
+ }
170
+ out
171
+ }
172
+
173
+ /// Shannon entropy in bits per byte, summed over byte values in order of first appearance
174
+ /// (the order of Python's Counter).
175
+ fn entropy_and_distinct(w: &[u8]) -> (f64, usize) {
176
+ let mut cnt = [0u32; 256];
177
+ let mut order = [0u8; 256];
178
+ let mut k = 0usize;
179
+ for &c in w {
180
+ if cnt[c as usize] == 0 {
181
+ order[k] = c;
182
+ k += 1;
183
+ }
184
+ cnt[c as usize] += 1;
185
+ }
186
+ let n = w.len() as f64;
187
+ let mut h = 0.0f64;
188
+ for &c in &order[..k] {
189
+ let p = cnt[c as usize] as f64 / n;
190
+ h += p * p.log2();
191
+ }
192
+ (-h, k)
193
+ }
194
+
195
+ /// Per window, `amanecer.salvage.regions.looks_random`: 1 / 0, or 2 when the entropy lies
196
+ /// within 1e-9 of its threshold (float summation order could differ; the caller decides).
197
+ /// Thresholds come from the caller, computed in Python: (dmin, emin) for full windows and for
198
+ /// the short last window.
199
+ pub fn random_flags(data: &[u8], gran: usize, full: (f64, f64), last: (f64, f64)) -> Vec<u8> {
200
+ let n = data.len();
201
+ if gran == 0 {
202
+ return Vec::new();
203
+ }
204
+ let mut out = Vec::with_capacity(n / gran + 1);
205
+ let mut i = 0usize;
206
+ while i < n {
207
+ let w = &data[i..(i + gran).min(n)];
208
+ let (dmin, emin) = if w.len() == gran { full } else { last };
209
+ let v = if w.len() < 16 {
210
+ 0
211
+ } else {
212
+ let (h, d) = entropy_and_distinct(w);
213
+ if (d as f64) < dmin {
214
+ 0
215
+ } else if (h - emin).abs() < 1e-9 {
216
+ 2
217
+ } else if h >= emin {
218
+ 1
219
+ } else {
220
+ 0
221
+ }
222
+ };
223
+ out.push(v);
224
+ i += gran;
225
+ }
226
+ out
227
+ }
228
+
229
+ #[inline]
230
+ fn is_weird(c: u8) -> bool {
231
+ c <= 8 || c == 0x0b || c == 0x0c || (0x0e..=0x1f).contains(&c) || c >= 0x7f
232
+ }
233
+
234
+ #[inline]
235
+ fn nonprint(w: &[u8]) -> usize {
236
+ w.iter().filter(|&&c| !is_text_byte(c)).count()
237
+ }
238
+
239
+ /// The tests of `amanecer.core.entropy.ciphertext_like` after the deflate test: text with a
240
+ /// run of control/high bytes, or a random-looking 256-byte window beside text or zeros.
241
+ pub fn cipher_mixed(b: &[u8]) -> bool {
242
+ if b.is_empty() {
243
+ return false;
244
+ }
245
+ let len = b.len() as f64;
246
+ let ascii_share = 1.0 - nonprint(b) as f64 / len;
247
+ if ascii_share >= 0.9 {
248
+ let mut run = 0;
249
+ for &c in b {
250
+ if is_weird(c) {
251
+ run += 1;
252
+ if run >= 3 {
253
+ return true;
254
+ }
255
+ } else {
256
+ run = 0;
257
+ }
258
+ }
259
+ }
260
+ let (mut random, mut text, mut zero) = (false, false, false);
261
+ let mut k = 0usize;
262
+ while k < b.len() {
263
+ let w = &b[k..(k + 256).min(b.len())];
264
+ k += 256;
265
+ if w.len() < 64 {
266
+ continue;
267
+ }
268
+ if w.iter().all(|&c| c == 0) {
269
+ zero = true;
270
+ continue;
271
+ }
272
+ let mut seen = [false; 256];
273
+ let mut d = 0usize;
274
+ for &c in w {
275
+ if !seen[c as usize] {
276
+ seen[c as usize] = true;
277
+ d += 1;
278
+ }
279
+ }
280
+ if d >= 120.min(w.len() * 15 / 32) {
281
+ random = true;
282
+ } else if 1.0 - nonprint(w) as f64 / w.len() as f64 >= 0.95 {
283
+ text = true;
284
+ }
285
+ }
286
+ random && (text || zero)
287
+ }
288
+
289
+ /// Offsets h in [start, end) with needle at h, h + len(needle) <= end and h % align == 0, in
290
+ /// order: `RawImage.find_all` over a buffer. Aligned needles are compared only at aligned
291
+ /// offsets (one probe per `align` bytes); unaligned ones use memchr's SIMD memmem.
292
+ pub fn find_all(hay: &[u8], needle: &[u8], align: usize, start: usize, end: usize) -> Vec<u64> {
293
+ let end = end.min(hay.len());
294
+ let mut out = Vec::new();
295
+ let k = needle.len();
296
+ if start > end || align == 0 || k == 0 || end - start < k {
297
+ return out;
298
+ }
299
+ if align >= 64 {
300
+ let mut i = start.div_ceil(align) * align;
301
+ while i + k <= end {
302
+ if hay[i] == needle[0] && &hay[i..i + k] == needle {
303
+ out.push(i as u64);
304
+ }
305
+ i += align;
306
+ }
307
+ } else {
308
+ let f = memchr::memmem::Finder::new(needle);
309
+ let mut pos = start;
310
+ while pos + k <= end {
311
+ match f.find(&hay[pos..end]) {
312
+ None => break,
313
+ Some(j) => {
314
+ let h = pos + j;
315
+ if h % align == 0 {
316
+ out.push(h as u64);
317
+ }
318
+ pos = h + 1;
319
+ }
320
+ }
321
+ }
322
+ }
323
+ out
324
+ }
325
+
326
+ /// `amanecer.containers.repair._find_bat`'s inner loop over one candidate MiB at file offset `o`:
327
+ /// (valid payload entries with distinct present offsets other than `o`, invalid entries in the
328
+ /// first 4 KiB).
329
+ pub fn vhdx_bat_score(raw: &[u8], fsize: u64, o: u64) -> (u64, u64) {
330
+ const MIB: u64 = 1 << 20;
331
+ let mut seen = std::collections::HashSet::new();
332
+ let (mut good, mut bad) = (0u64, 0u64);
333
+ let mut k = 0usize;
334
+ while k + 8 <= raw.len() {
335
+ let v = u64::from_le_bytes(raw[k..k + 8].try_into().unwrap());
336
+ let state = v & 7;
337
+ let off = (v >> 20) << 20;
338
+ let ok = if (v >> 3) & ((1 << 17) - 1) != 0 {
339
+ false
340
+ } else if !matches!(state, 0 | 1 | 2 | 3 | 6 | 7) {
341
+ false
342
+ } else if state == 6 || state == 7 {
343
+ MIB <= off && off < fsize
344
+ } else {
345
+ off == 0 || state == 3
346
+ };
347
+ if k < 4096 && !ok {
348
+ bad += 1;
349
+ }
350
+ if ok && (state == 6 || state == 7) && off != o && seen.insert(off) {
351
+ good += 1;
352
+ }
353
+ k += 8;
354
+ }
355
+ (good, bad)
356
+ }
357
+
358
+ /// Same refusal as the Python decoder: a block stating more than 256 MiB (snap would allocate the
359
+ /// stated length up front, up to 4 GiB, before finding the input short).
360
+ pub const SNAPPY_MAX: usize = 1 << 28;
361
+
362
+ pub fn snappy_decompress(src: &[u8]) -> Result<Vec<u8>, String> {
363
+ match snap::raw::decompress_len(src) {
364
+ Ok(n) if n > SNAPPY_MAX => return Err("snappy: stated length too large".into()),
365
+ Err(e) => return Err(format!("snappy: {e}")),
366
+ _ => {}
367
+ }
368
+ snap::raw::Decoder::new()
369
+ .decompress_vec(src)
370
+ .map_err(|e| format!("snappy: {e}"))
371
+ }
372
+
373
+ pub fn lz4_block_decompress(src: &[u8], max_out: usize) -> Result<Vec<u8>, String> {
374
+ lz4_flex::block::decompress(src, max_out).map_err(|e| format!("lz4: {e}"))
375
+ }
376
+
377
+ pub fn snappy_compress(src: &[u8]) -> Vec<u8> {
378
+ snap::raw::Encoder::new()
379
+ .compress_vec(src)
380
+ .unwrap_or_default()
381
+ }
382
+
383
+ pub fn lz4_compress(src: &[u8]) -> Vec<u8> {
384
+ lz4_flex::block::compress(src)
385
+ }
386
+
387
+ #[cfg(test)]
388
+ mod tests {
389
+ use super::*;
390
+
391
+ #[test]
392
+ fn crc32c_known() {
393
+ assert_eq!(crc32c(b"123456789", 0), 0xE306_9283);
394
+ assert_eq!(crc32c(b"6789", crc32c(b"12345", 0)), 0xE306_9283);
395
+ }
396
+
397
+ #[test]
398
+ fn pst_crc_known() {
399
+ // zlib.crc32(b"123456789", 0xFFFFFFFF) ^ 0xFFFFFFFF
400
+ let mut h = crc32fast::Hasher::new_with_initial(0xFFFF_FFFF);
401
+ h.update(b"123456789");
402
+ assert_eq!(pst_crc(b"123456789"), h.finalize() ^ 0xFFFF_FFFF);
403
+ }
404
+
405
+ #[test]
406
+ fn text_basic() {
407
+ assert_eq!(text_flags(b"hello wo\x01\x02rld ", 8), vec![1, 0]);
408
+ assert_eq!(text_flags("caf\u{e9} ok!".as_bytes(), 8), vec![2, 1]);
409
+ }
410
+ }
@@ -0,0 +1,189 @@
1
+ //! amanecer_native: optional compiled kernels. See amanecer/core/native.py for how they are
2
+ //! selected and kernels.rs for what each one mirrors.
3
+ pub mod kernels;
4
+
5
+ #[cfg(feature = "salvage-zlib")]
6
+ pub mod salvage_zlib;
7
+
8
+ #[cfg(feature = "python")]
9
+ mod py {
10
+ use super::kernels as k;
11
+ use pyo3::buffer::PyBuffer;
12
+ use pyo3::exceptions::PyValueError;
13
+ use pyo3::prelude::*;
14
+ use pyo3::types::PyBytes;
15
+
16
+ /// Borrow any contiguous byte buffer (bytes, bytearray, memoryview, mmap) without copying.
17
+ /// The exporter keeps the memory alive (and an mmap from closing) while `buf` lives.
18
+ fn slice<'a>(buf: &'a PyBuffer<u8>) -> PyResult<&'a [u8]> {
19
+ if !buf.is_c_contiguous() {
20
+ return Err(PyValueError::new_err("buffer must be contiguous"));
21
+ }
22
+ let n = buf.len_bytes();
23
+ if n == 0 {
24
+ return Ok(&[]);
25
+ }
26
+ // SAFETY: a contiguous u8 buffer of n bytes, held exported for the borrow's lifetime.
27
+ Ok(unsafe { std::slice::from_raw_parts(buf.buf_ptr() as *const u8, n) })
28
+ }
29
+
30
+ #[pyfunction]
31
+ #[pyo3(name = "crc32c", signature = (data, crc=0))]
32
+ fn py_crc32c(py: Python<'_>, data: &Bound<'_, PyAny>, crc: u32) -> PyResult<u32> {
33
+ let b = PyBuffer::<u8>::get(data)?;
34
+ let s = slice(&b)?;
35
+ Ok(if s.len() > 1 << 16 {
36
+ py.detach(|| k::crc32c(s, crc))
37
+ } else {
38
+ k::crc32c(s, crc)
39
+ })
40
+ }
41
+
42
+ #[pyfunction]
43
+ fn pst_crc(data: &Bound<'_, PyAny>) -> PyResult<u32> {
44
+ let b = PyBuffer::<u8>::get(data)?;
45
+ Ok(k::pst_crc(slice(&b)?))
46
+ }
47
+
48
+ /// (page_candidates, [(start, cb, bid)], bad_crc)
49
+ #[pyfunction]
50
+ fn pst_scan(
51
+ py: Python<'_>,
52
+ data: &Bound<'_, PyAny>,
53
+ page: usize,
54
+ trailer: usize,
55
+ align: usize,
56
+ block_trailer: usize,
57
+ max_cb: usize,
58
+ ) -> PyResult<(Vec<u64>, Vec<(u64, u32, u64)>, u64)> {
59
+ let b = PyBuffer::<u8>::get(data)?;
60
+ let s = slice(&b)?;
61
+ let l = k::PstLayout {
62
+ page,
63
+ trailer,
64
+ align,
65
+ block_trailer,
66
+ max_cb,
67
+ };
68
+ let r = py.detach(|| k::pst_scan(s, &l));
69
+ Ok((r.pages, r.blocks, r.bad_crc))
70
+ }
71
+
72
+ #[pyfunction]
73
+ fn text_flags<'py>(
74
+ py: Python<'py>,
75
+ data: &Bound<'py, PyAny>,
76
+ gran: usize,
77
+ ) -> PyResult<Bound<'py, PyBytes>> {
78
+ let b = PyBuffer::<u8>::get(data)?;
79
+ let s = slice(&b)?;
80
+ let v = py.detach(|| k::text_flags(s, gran));
81
+ Ok(PyBytes::new(py, &v))
82
+ }
83
+
84
+ #[pyfunction]
85
+ fn random_flags<'py>(
86
+ py: Python<'py>,
87
+ data: &Bound<'py, PyAny>,
88
+ gran: usize,
89
+ full: (f64, f64),
90
+ last: (f64, f64),
91
+ ) -> PyResult<Bound<'py, PyBytes>> {
92
+ let b = PyBuffer::<u8>::get(data)?;
93
+ let s = slice(&b)?;
94
+ let v = py.detach(|| k::random_flags(s, gran, full, last));
95
+ Ok(PyBytes::new(py, &v))
96
+ }
97
+
98
+ #[pyfunction]
99
+ fn cipher_mixed(data: &Bound<'_, PyAny>) -> PyResult<bool> {
100
+ let b = PyBuffer::<u8>::get(data)?;
101
+ Ok(k::cipher_mixed(slice(&b)?))
102
+ }
103
+
104
+ fn bytes_result<'py>(
105
+ py: Python<'py>,
106
+ r: Result<Vec<u8>, String>,
107
+ ) -> PyResult<Bound<'py, PyBytes>> {
108
+ r.map(|v| PyBytes::new(py, &v))
109
+ .map_err(PyValueError::new_err)
110
+ }
111
+
112
+ #[pyfunction]
113
+ fn snappy_decompress<'py>(
114
+ py: Python<'py>,
115
+ data: &Bound<'py, PyAny>,
116
+ ) -> PyResult<Bound<'py, PyBytes>> {
117
+ let b = PyBuffer::<u8>::get(data)?;
118
+ let s = slice(&b)?;
119
+ let r = py.detach(|| k::snappy_decompress(s));
120
+ bytes_result(py, r)
121
+ }
122
+
123
+ #[pyfunction]
124
+ fn lz4_block_decompress<'py>(
125
+ py: Python<'py>,
126
+ data: &Bound<'py, PyAny>,
127
+ max_out: usize,
128
+ ) -> PyResult<Bound<'py, PyBytes>> {
129
+ let b = PyBuffer::<u8>::get(data)?;
130
+ let s = slice(&b)?;
131
+ let r = py.detach(|| k::lz4_block_decompress(s, max_out));
132
+ bytes_result(py, r)
133
+ }
134
+
135
+ #[pyfunction]
136
+ fn snappy_compress<'py>(
137
+ py: Python<'py>,
138
+ data: &Bound<'py, PyAny>,
139
+ ) -> PyResult<Bound<'py, PyBytes>> {
140
+ let b = PyBuffer::<u8>::get(data)?;
141
+ Ok(PyBytes::new(py, &k::snappy_compress(slice(&b)?)))
142
+ }
143
+
144
+ #[pyfunction]
145
+ fn lz4_compress<'py>(
146
+ py: Python<'py>,
147
+ data: &Bound<'py, PyAny>,
148
+ ) -> PyResult<Bound<'py, PyBytes>> {
149
+ let b = PyBuffer::<u8>::get(data)?;
150
+ Ok(PyBytes::new(py, &k::lz4_compress(slice(&b)?)))
151
+ }
152
+
153
+ #[pyfunction]
154
+ fn find_all(
155
+ py: Python<'_>,
156
+ data: &Bound<'_, PyAny>,
157
+ needle: &[u8],
158
+ align: usize,
159
+ start: usize,
160
+ end: usize,
161
+ ) -> PyResult<Vec<u64>> {
162
+ let b = PyBuffer::<u8>::get(data)?;
163
+ let s = slice(&b)?;
164
+ Ok(py.detach(|| k::find_all(s, needle, align, start, end)))
165
+ }
166
+
167
+ #[pyfunction]
168
+ fn vhdx_bat_score(data: &Bound<'_, PyAny>, fsize: u64, o: u64) -> PyResult<(u64, u64)> {
169
+ let b = PyBuffer::<u8>::get(data)?;
170
+ Ok(k::vhdx_bat_score(slice(&b)?, fsize, o))
171
+ }
172
+
173
+ #[pymodule]
174
+ fn amanecer_native(m: &Bound<'_, PyModule>) -> PyResult<()> {
175
+ m.add_function(wrap_pyfunction!(py_crc32c, m)?)?;
176
+ m.add_function(wrap_pyfunction!(pst_crc, m)?)?;
177
+ m.add_function(wrap_pyfunction!(find_all, m)?)?;
178
+ m.add_function(wrap_pyfunction!(vhdx_bat_score, m)?)?;
179
+ m.add_function(wrap_pyfunction!(pst_scan, m)?)?;
180
+ m.add_function(wrap_pyfunction!(text_flags, m)?)?;
181
+ m.add_function(wrap_pyfunction!(random_flags, m)?)?;
182
+ m.add_function(wrap_pyfunction!(cipher_mixed, m)?)?;
183
+ m.add_function(wrap_pyfunction!(snappy_decompress, m)?)?;
184
+ m.add_function(wrap_pyfunction!(lz4_block_decompress, m)?)?;
185
+ m.add_function(wrap_pyfunction!(snappy_compress, m)?)?;
186
+ m.add_function(wrap_pyfunction!(lz4_compress, m)?)?;
187
+ Ok(())
188
+ }
189
+ }
@@ -0,0 +1,47 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ //! Stock zlib encoder for byte-identical recovery of PNG row prefixes.
3
+
4
+ use libz_sys::{compress2, compressBound, uLong, Z_DEFAULT_COMPRESSION, Z_OK};
5
+ use std::io;
6
+
7
+ pub fn compress(data: &[u8]) -> io::Result<Vec<u8>> {
8
+ compress_at_level(data, Z_DEFAULT_COMPRESSION)
9
+ }
10
+
11
+ pub fn compress_at_level(data: &[u8], level: i32) -> io::Result<Vec<u8>> {
12
+ let input = uLong::try_from(data.len())
13
+ .map_err(|_| io::Error::other("PNG row data exceeds the zlib input limit"))?;
14
+ // SAFETY: compressBound accepts an integer and does not borrow memory.
15
+ let mut written = unsafe { compressBound(input) };
16
+ let capacity = usize::try_from(written)
17
+ .ok()
18
+ .filter(|&bound| bound >= data.len())
19
+ .ok_or_else(|| io::Error::other("PNG zlib output bound exceeds the platform limit"))?;
20
+ let mut output = Vec::new();
21
+ output
22
+ .try_reserve_exact(capacity)
23
+ .map_err(io::Error::other)?;
24
+ output.resize(capacity, 0);
25
+ // SAFETY: input and output are disjoint initialized buffers of the lengths
26
+ // given to zlib. The output pointer and the size stay valid for this call.
27
+ let status = unsafe {
28
+ compress2(
29
+ output.as_mut_ptr(),
30
+ &mut written,
31
+ data.as_ptr(),
32
+ input,
33
+ level,
34
+ )
35
+ };
36
+ if status != Z_OK {
37
+ return Err(io::Error::other(format!(
38
+ "PNG zlib compression failed ({status})"
39
+ )));
40
+ }
41
+ let written = usize::try_from(written)
42
+ .ok()
43
+ .filter(|&size| size <= capacity)
44
+ .ok_or_else(|| io::Error::other("PNG zlib returned an invalid output size"))?;
45
+ output.truncate(written);
46
+ Ok(output)
47
+ }