asc-apk 0.2.1

Memory-mapped APK access for asc-rs: central-directory scan, root-level DEX enumeration and (cancellable) Deflate extraction.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
//! Read-only APK (zip) access.
//!
//! The archive is memory-mapped and only its central directory is walked.
//! Entries are extracted on demand: stored entries are borrowed straight from
//! the mapping, Deflate entries are inflated (optionally with a cancellation
//! flag; the streaming decoder polls it on every input read, the libdeflate
//! path once per entry, so a parallel class search can abandon the remaining
//! DEX files as soon as one worker hits).
//!
//! Several archives can also be read as one program ([`Apk::open`]).

mod program;

pub use program::Version;

use memmap2::Mmap;
use std::borrow::Cow;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::SystemTime;

const CD_SIG: &[u8; 4] = b"PK\x01\x02";
const LH_SIG: &[u8; 4] = b"PK\x03\x04";
const EOCD_SIG: &[u8; 4] = b"PK\x05\x06";
const ZIP64_EOCD_SIG: &[u8; 4] = b"PK\x06\x06";
const ZIP64_LOCATOR_SIG: &[u8; 4] = b"PK\x06\x07";
const DEFLATE_CHUNK: usize = 1 << 19;
/// Deflate cannot expand data by more than about 1032:1; a central directory
/// claiming more is corrupt or hostile and must not drive an allocation.
const MAX_DEFLATE_RATIO: u64 = 1032;
/// A declared size is reserved up front only up to the larger of this and
/// [`TYPICAL_RATIO`] times the compressed payload; anything bigger grows on
/// demand, so a lying central directory cannot force a large allocation
/// while real DEX entries still get a single exact one.
const INITIAL_CAPACITY: usize = 64 << 20;
/// Real DEX files inflate well under this ratio.
const TYPICAL_RATIO: usize = 16;

/// Zip compression method 0: the entry is stored uncompressed.
pub const METHOD_STORED: u16 = 0;
/// Zip compression method 8: the entry is Deflate-compressed.
pub const METHOD_DEFLATE: u16 = 8;

/// Why an archive could not be opened or an entry read.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ApkError {
    /// Opening, mapping or reading the metadata of a file failed.
    #[error("io error on {path}: {source}")]
    Io {
        /// The file or directory.
        path: PathBuf,
        /// The underlying error.
        source: std::io::Error,
    },
    /// No end-of-central-directory record: not a zip, or truncated.
    #[error("end of central directory not found")]
    NoEocd,
    /// The central directory lies outside the file.
    #[error("central directory out of range")]
    BadCentralDirectory,
    /// The local header of the named entry is missing or its payload runs
    /// past the end of the file.
    #[error("bad local header signature for entry {0}")]
    BadLocalHeader(String),
    /// A compression method other than stored or Deflate.
    #[error("unsupported compression method {0}")]
    UnsupportedMethod(u16),
    /// The Deflate stream of an entry is corrupt.
    #[error("inflate failed for entry {name}: {source}")]
    Inflate {
        /// The entry name.
        name: String,
        /// The decoder's error.
        source: std::io::Error,
    },
    /// An entry's data is not as long as the central directory says.
    #[error("size mismatch for entry {name}: expected {expected}, got {actual}")]
    SizeMismatch {
        /// The entry name.
        name: String,
        /// Uncompressed size in bytes from the central directory.
        expected: usize,
        /// Bytes actually read or inflated.
        actual: usize,
    },
    /// No entry of that name.
    #[error("entry {0} not found")]
    NotFound(String),
    /// An entry declares (or inflates to) more than Deflate can produce from
    /// its compressed size: a corrupt or hostile central directory.
    #[error("entry {name} declares an implausible size (compressed {comp_size}, uncompressed {uncomp_size})")]
    ImplausibleSize {
        /// The entry name.
        name: String,
        /// Compressed size in bytes.
        comp_size: u64,
        /// Declared uncompressed size in bytes.
        uncomp_size: u64,
    },
    /// An entry, or the DEX entries together, exceed the configured
    /// [`Limits`].
    #[error("entry {name} exceeds the inflate limit: {reason}")]
    LimitExceeded {
        /// The entry name (`classes*.dex` for the DEX total).
        name: String,
        /// Which limit, and by how much.
        reason: String,
    },
    /// The caller's cancellation flag was raised.
    #[error("cancelled")]
    Cancelled,
    /// A program path where no archive has root DEX entries.
    #[error("no archive of {} has classes*.dex ({})", path.display(), notes.join("; "))]
    NoCode {
        /// The path as given to [`Apk::open`].
        path: PathBuf,
        /// Why each archive was left out, one line each.
        notes: Vec<String>,
    },
}

/// `Result` with [`ApkError`].
pub type Result<T> = std::result::Result<T, ApkError>;

/// One central-directory entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Entry {
    /// Name inside the archive; in a program, prefixed with the archive's
    /// label (`services.jar/classes.dex`).
    pub name: String,
    /// Compression method ([`METHOD_STORED`], [`METHOD_DEFLATE`], ...).
    pub method: u16,
    /// Compressed size in bytes (zip64 sizes resolved).
    pub comp_size: u64,
    /// Uncompressed size in bytes as declared; 0 may mean unknown.
    pub uncomp_size: u64,
    /// Offset of the entry's local file header in its archive.
    pub local_header_off: u64,
    /// CRC-32 of the uncompressed data, as the central directory records it.
    pub crc32: u32,
    /// The archive of a program it belongs to ([`Apk::archive_path`]).
    pub archive: usize,
}

/// Caps on what reading an APK may inflate, against zip bombs. The default
/// only rejects what Deflate cannot produce; [`Limits::guarded`] is for
/// sweeping untrusted APKs in bulk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
    /// Most bytes one entry may inflate to.
    pub max_entry_bytes: u64,
    /// Most an entry may expand over its compressed payload.
    pub max_ratio: u64,
    /// Most bytes all root DEX entries together may declare.
    pub max_dex_total_bytes: u64,
}

impl Default for Limits {
    fn default() -> Limits {
        Limits::new()
    }
}

impl Limits {
    /// The default: only what Deflate cannot produce is rejected. A
    /// `const fn`, so that with the setters below limits can be constants.
    pub const fn new() -> Limits {
        Limits { max_entry_bytes: u64::MAX, max_ratio: MAX_DEFLATE_RATIO, max_dex_total_bytes: u64::MAX }
    }

    /// Real DEX files are at most a few hundred MiB and compress 2-5:1.
    pub const fn guarded() -> Limits {
        Limits { max_entry_bytes: 1 << 30, max_ratio: 100, max_dex_total_bytes: 4 << 30 }
    }

    /// These limits with at most `bytes` inflated per entry.
    #[must_use]
    pub const fn max_entry_bytes(self, bytes: u64) -> Limits {
        Limits { max_entry_bytes: bytes, ..self }
    }

    /// These limits with an entry expanding at most `ratio` times its
    /// compressed payload.
    #[must_use]
    pub const fn max_ratio(self, ratio: u64) -> Limits {
        Limits { max_ratio: ratio, ..self }
    }

    /// These limits with at most `bytes` declared by all root DEX entries
    /// together.
    #[must_use]
    pub const fn max_dex_total_bytes(self, bytes: u64) -> Limits {
        Limits { max_dex_total_bytes: bytes, ..self }
    }
}

/// A memory-mapped APK, or several archives (APKs, jars, bare DEX files)
/// read as one program: see [`Apk::open`]. Clones share the mappings, so a
/// host can keep one open and hand out copies while [`Apk::version`] holds.
#[derive(Clone)]
pub struct Apk {
    path: PathBuf,
    archives: Arc<[Archive]>,
    limits: Limits,
    /// Archives of a program left out of its code, one line each.
    notes: Arc<[String]>,
    version: Version,
}

/// One archive of an [`Apk`] as a cache key sees it ([`Apk::directories`]).
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ArchiveId<'a> {
    /// The archive's file.
    pub path: &'a Path,
    /// What its entry names start with in a program ([`archive_of`]); empty
    /// for a lone archive.
    pub label: &'a str,
    /// Its central directory, or a bare DEX file's header.
    pub directory: &'a [u8],
}

/// One file of an [`Apk`].
struct Archive {
    path: PathBuf,
    map: Data,
    /// Its name in a program of several archives (`services.jar`,
    /// `app/TeleService/TeleService.apk`), which prefixes its entry names;
    /// empty for a lone archive.
    label: String,
    /// A bare DEX file rather than a zip: one stored entry, the whole file.
    bare_dex: bool,
}

/// The bytes of one archive: a mapped file, or an entry of another archive
/// that is itself an archive ([`Apk::open_nested`]).
enum Data {
    Mapped(Mmap),
    /// A stored entry, read in place: `range` of archive `archive` of `outer`.
    Window {
        outer: Arc<[Archive]>,
        archive: usize,
        range: std::ops::Range<usize>,
    },
    /// An inflated entry.
    Owned(Vec<u8>),
}

impl std::ops::Deref for Data {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        match self {
            Data::Mapped(map) => map,
            // The range was taken from this very archive when the window was made.
            Data::Window { outer, archive, range } => &outer[*archive].map[range.clone()],
            Data::Owned(bytes) => bytes,
        }
    }
}

/// `n` bytes at `o`, or `None` if they are not all inside `b` (offsets come
/// from the archive, so the addition itself must not be trusted either).
#[inline]
fn bytes_at(b: &[u8], o: usize, n: usize) -> Option<&[u8]> {
    b.get(o..o.checked_add(n)?)
}
#[inline]
fn u16_at(b: &[u8], o: usize) -> Option<u16> {
    bytes_at(b, o, 2).map(|s| u16::from_le_bytes([s[0], s[1]]))
}
#[inline]
fn u32_at(b: &[u8], o: usize) -> Option<u32> {
    bytes_at(b, o, 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
#[inline]
fn u64_at(b: &[u8], o: usize) -> Option<u64> {
    bytes_at(b, o, 8).map(|s| u64::from_le_bytes(s.try_into().expect("8 bytes")))
}
/// A `u64` archive offset as `usize`, or `None` when it cannot even be
/// represented (32-bit hosts).
#[inline]
fn offset(v: u64) -> Option<usize> {
    usize::try_from(v).ok()
}

/// The archive of a program a DEX of it comes from, by the DEX's name
/// (`app/Tele.apk` for `app/Tele.apk/classes2.dex`, also as a logical DEX
/// `...classes2.dex!classes1.dex`); `None` for a lone archive's.
pub fn archive_of(dex_name: &str) -> Option<&str> {
    let entry = dex_name.split('!').next().unwrap_or(dex_name);
    entry.rsplit_once('/').map(|(archive, _)| archive)
}

/// Whether `name` (inside one archive) is a root-level `*.dex`
/// (`classes.dex`, `classes2.dex`, ...).
fn is_root_dex(name: &[u8]) -> bool {
    name.ends_with(b".dex") && !name.contains(&b'/')
}

/// Whether `name` (inside one archive) is a `*.dex` at any depth
/// (`classes.dex`, `assets/payload.dex`, ...).
fn is_any_dex(name: &[u8]) -> bool {
    name.ends_with(b".dex")
}

/// Where a root DEX entry falls in the runtime's multidex order:
/// `classes.dex` is 1, `classesN.dex` is N, anything else comes last. `name`
/// may carry a program's archive prefix.
fn multidex_rank(name: &str) -> u32 {
    let file = name.rsplit('/').next().unwrap_or(name);
    match file.strip_prefix("classes").and_then(|rest| rest.strip_suffix(".dex")) {
        Some("") => 1,
        Some(n) if n.bytes().all(|b| b.is_ascii_digit()) && !n.starts_with('0') => n.parse().unwrap_or(u32::MAX),
        _ => u32::MAX,
    }
}

/// The one entry of a bare DEX file, by its name inside the archive.
const BARE_DEX_ENTRY: &str = "classes.dex";
/// Size of the DEX header, which carries the file's checksum and SHA-1.
const DEX_HEADER_SIZE: usize = 0x70;

impl Archive {
    fn open(path: PathBuf, label: String) -> Result<Archive> {
        let file = File::open(&path).map_err(|source| ApkError::Io { path: path.clone(), source })?;
        // SAFETY: the mapping is read-only and the file is not expected to be
        // modified while it is mapped (same contract as the Python mmap use).
        let map = unsafe { Mmap::map(&file) }.map_err(|source| ApkError::Io { path: path.clone(), source })?;
        let bare_dex = map.starts_with(b"dex\n");
        Ok(Archive { path, map: Data::Mapped(map), label, bare_dex })
    }

    /// `inner` (a name inside this archive) as the program names it:
    /// `label/inner`, so the archive is all before the last `/`.
    fn entry_name(&self, inner: &[u8]) -> String {
        let inner = String::from_utf8_lossy(inner);
        if self.label.is_empty() { inner.into_owned() } else { format!("{}/{inner}", self.label) }
    }

    /// The name inside this archive of the program's entry `name`, if it
    /// names one of this archive's entries.
    fn inner_name<'n>(&self, name: &'n str) -> Option<&'n str> {
        if self.label.is_empty() {
            return None;
        }
        name.strip_prefix(self.label.as_str())?.strip_prefix('/')
    }

    /// Locate the central directory as `(offset, size)`, honouring zip64.
    fn central_directory(&self) -> Result<(usize, usize)> {
        let data = &self.map[..];
        let search_start = data.len().saturating_sub(65536 + 22);
        let eocd = memchr::memmem::rfind(&data[search_start..], EOCD_SIG).map(|p| p + search_start).ok_or(ApkError::NoEocd)?;
        let mut cd_size = u32_at(data, eocd + 12).ok_or(ApkError::NoEocd)? as u64;
        let mut cd_off = u32_at(data, eocd + 16).ok_or(ApkError::NoEocd)? as u64;
        if cd_size == 0xFFFF_FFFF || cd_off == 0xFFFF_FFFF {
            // zip64: locator sits right before the EOCD.
            if eocd >= 20 && &data[eocd - 20..eocd - 16] == ZIP64_LOCATOR_SIG {
                let rec = u64_at(data, eocd - 20 + 8).and_then(offset).ok_or(ApkError::NoEocd)?;
                if bytes_at(data, rec, 4) == Some(ZIP64_EOCD_SIG) {
                    cd_size = rec.checked_add(40).and_then(|o| u64_at(data, o)).ok_or(ApkError::NoEocd)?;
                    cd_off = rec.checked_add(48).and_then(|o| u64_at(data, o)).ok_or(ApkError::NoEocd)?;
                }
            }
        }
        let (Some(off), Some(size)) = (offset(cd_off), offset(cd_size)) else {
            return Err(ApkError::BadCentralDirectory);
        };
        if off.checked_add(size).map(|e| e > data.len()).unwrap_or(true) {
            return Err(ApkError::BadCentralDirectory);
        }
        Ok((off, size))
    }

    /// What identifies this version of the archive: its central directory,
    /// or a bare DEX file's header.
    fn directory(&self) -> Result<&[u8]> {
        if self.bare_dex {
            return Ok(&self.map[..self.map.len().min(DEX_HEADER_SIZE)]);
        }
        let (off, size) = self.central_directory()?;
        Ok(&self.map[off..off + size])
    }

    /// Walk the central directory, `keep` filtering by the name inside this
    /// archive; the entries are of archive `index` of the program.
    fn entries_filtered(&self, index: usize, keep: &mut impl FnMut(&[u8]) -> bool) -> Result<Vec<Entry>> {
        if self.bare_dex {
            if !keep(BARE_DEX_ENTRY.as_bytes()) {
                return Ok(Vec::new());
            }
            let len = self.map.len() as u64;
            return Ok(vec![Entry {
                name: self.entry_name(BARE_DEX_ENTRY.as_bytes()),
                method: METHOD_STORED,
                comp_size: len,
                uncomp_size: len,
                local_header_off: 0,
                crc32: 0,
                archive: index,
            }]);
        }
        let data = &self.map[..];
        let (cd_off, cd_size) = self.central_directory()?;
        let cd_end = cd_off + cd_size;
        let mut entries = Vec::new();
        let mut p = cd_off;
        while p + 46 <= cd_end {
            if &data[p..p + 4] != CD_SIG {
                break;
            }
            let name_len = u16_at(data, p + 28).unwrap_or(0) as usize;
            let extra_len = u16_at(data, p + 30).unwrap_or(0) as usize;
            let comment_len = u16_at(data, p + 32).unwrap_or(0) as usize;
            let name_start = p + 46;
            let name_end = name_start + name_len;
            if name_end > cd_end {
                break;
            }
            let name = &data[name_start..name_end];
            if keep(name) {
                let mut comp_size = u32_at(data, p + 20).unwrap_or(0) as u64;
                let mut uncomp_size = u32_at(data, p + 24).unwrap_or(0) as u64;
                let mut local_header_off = u32_at(data, p + 42).unwrap_or(0) as u64;
                if comp_size == 0xFFFF_FFFF || uncomp_size == 0xFFFF_FFFF || local_header_off == 0xFFFF_FFFF {
                    // zip64 extra field (id 0x0001).
                    let mut q = name_end;
                    let extra_end = name_end + extra_len;
                    while q + 4 <= extra_end {
                        let id = u16_at(data, q).unwrap_or(0);
                        let len = u16_at(data, q + 2).unwrap_or(0) as usize;
                        if id == 0x0001 {
                            let mut r = q + 4;
                            if uncomp_size == 0xFFFF_FFFF {
                                uncomp_size = u64_at(data, r).unwrap_or(0);
                                r += 8;
                            }
                            if comp_size == 0xFFFF_FFFF {
                                comp_size = u64_at(data, r).unwrap_or(0);
                                r += 8;
                            }
                            if local_header_off == 0xFFFF_FFFF {
                                local_header_off = u64_at(data, r).unwrap_or(0);
                            }
                            break;
                        }
                        q += 4 + len;
                    }
                }
                entries.push(Entry {
                    name: self.entry_name(name),
                    method: u16_at(data, p + 10).unwrap_or(0),
                    comp_size,
                    uncomp_size,
                    local_header_off,
                    crc32: u32_at(data, p + 16).unwrap_or(0),
                    archive: index,
                });
            }
            p = name_end + extra_len + comment_len;
        }
        Ok(entries)
    }

    /// Root-level DEX entries in central-directory order. Duplicate names
    /// keep the last occurrence, like [`Apk::find_entry`] (and `zipfile`).
    fn dex_entries_in_order(&self, index: usize) -> Result<Vec<Entry>> {
        self.dex_entries_matching(index, is_root_dex)
    }

    /// The entries `is_dex` accepts by name, in central-directory order,
    /// duplicate names keeping the last occurrence.
    fn dex_entries_matching(&self, index: usize, mut is_dex: fn(&[u8]) -> bool) -> Result<Vec<Entry>> {
        let mut entries = self.entries_filtered(index, &mut is_dex)?;
        // Last occurrence wins: walk from the back keeping first-seen names.
        entries.reverse();
        let mut seen = std::collections::HashSet::with_capacity(entries.len());
        entries.retain(|e| seen.insert(e.name.clone()));
        entries.reverse();
        Ok(entries)
    }
}

impl Apk {
    /// Open `path` read-only: an APK (any zip, e.g. a jar), a bare DEX file,
    /// or a program of several archives read as one:
    ///
    /// - a directory: every `*.apk`, `*.jar`, `*.zip` and `*.dex` below it;
    /// - several paths (files or directories) joined with `,`, when no file
    ///   of that whole name exists.
    ///
    /// A program's entries are named after their archive
    /// (`services.jar/classes2.dex`, `x.dex/classes.dex` for a bare DEX
    /// file; see [`archive_of`]). Archives without root DEX entries, or
    /// that do not open, are left out and named in [`Apk::notes`]; a program
    /// none of whose archives has code is an error. A program that comes
    /// down to one archive is that archive alone.
    ///
    /// # Errors
    ///
    /// [`ApkError::Io`] when a path cannot be read or a lone archive cannot
    /// be mapped, [`ApkError::NoCode`] for a directory without archives or a
    /// program none of whose archives has code.
    pub fn open(path: impl AsRef<Path>) -> Result<Apk> {
        let path = path.as_ref().to_path_buf();
        let sources = program::sources(&path)?;
        let version = Version::of_sources(&sources);
        if let [lone] = &sources[..] {
            let archives = Arc::new([Archive::open(lone.path.clone(), String::new())?]);
            return Ok(Apk { path, archives, limits: Limits::default(), notes: Arc::new([]), version });
        }
        let mut archives = Vec::with_capacity(sources.len());
        let mut notes = Vec::new();
        for s in sources {
            let archive = match Archive::open(s.path, s.label) {
                Ok(a) => a,
                Err(e) => {
                    notes.push(format!("skipped: {e}"));
                    continue;
                }
            };
            match archive.dex_entries_in_order(archives.len()) {
                Ok(dex) if dex.is_empty() => notes.push(format!("{}: no classes*.dex (odex/vdex only?): deodex first", archive.label)),
                Ok(_) => archives.push(archive),
                Err(e) => notes.push(format!("{}: skipped: {e}", archive.label)),
            }
        }
        if archives.is_empty() {
            return Err(ApkError::NoCode { path, notes });
        }
        if let [lone] = &mut archives[..] {
            lone.label.clear();
        }
        Ok(Apk { path, archives: archives.into(), limits: Limits::default(), notes: notes.into(), version })
    }

    /// Read `bytes` as a lone archive (or bare DEX file) already in memory,
    /// as [`Apk::open`] reads a file; `path` only names it. Its
    /// [`Apk::version`] lists no file.
    pub fn from_bytes(path: impl Into<PathBuf>, bytes: Vec<u8>) -> Apk {
        let path = path.into();
        let bare_dex = bytes.starts_with(b"dex\n");
        let archive = Archive { path: path.clone(), map: Data::Owned(bytes), label: String::new(), bare_dex };
        Apk { path, archives: Arc::new([archive]), limits: Limits::default(), notes: Arc::new([]), version: Version::in_memory() }
    }

    /// The files `path` (as [`Apk::open`] takes it) names now, with their
    /// sizes and modification times: equal to an open [`Apk::version`]
    /// when opening again would read the same files. Costs a directory walk
    /// and a `stat` per archive, not a mapping.
    ///
    /// # Errors
    ///
    /// [`ApkError::Io`] when a path cannot be read, [`ApkError::NoCode`] for
    /// a directory without archives.
    pub fn version_of(path: impl AsRef<Path>) -> Result<Version> {
        Ok(Version::of_sources(&program::sources(path.as_ref())?))
    }

    /// The files read and their sizes and times when this was opened.
    pub fn version(&self) -> &Version {
        &self.version
    }

    /// `spec` (a path [`Apk::open`] takes) with its relative paths resolved
    /// against `base`: each of several paths joined with `,` on its own.
    pub fn resolve(spec: &Path, base: &Path) -> PathBuf {
        program::resolve(spec, base)
    }

    /// Enforce `limits` on every later read.
    pub fn with_limits(mut self, limits: Limits) -> Apk {
        self.limits = limits;
        self
    }

    /// The path the APK was opened from (a program's directory or list).
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// The limits every read enforces ([`Apk::with_limits`]).
    pub fn limits(&self) -> Limits {
        self.limits
    }

    /// How many archives make up the program: 1 for a lone archive, whose
    /// entry names are the names inside it.
    pub fn archive_count(&self) -> usize {
        self.archives.len()
    }

    /// One line per archive of a program left out of its code.
    pub fn notes(&self) -> &[String] {
        &self.notes
    }

    /// The file `entry` lives in.
    pub fn archive_path(&self, entry: &Entry) -> &Path {
        &self.archive(entry).path
    }

    /// The raw bytes of the file `entry` lives in.
    pub fn archive_data(&self, entry: &Entry) -> &[u8] {
        &self.archive(entry).map
    }

    fn archive(&self, entry: &Entry) -> &Archive {
        self.archives.get(entry.archive).expect("entry of this APK")
    }

    /// What identifies each archive's version, in program order. A cache key
    /// hashes them.
    ///
    /// # Errors
    ///
    /// [`ApkError::NoEocd`] or [`ApkError::BadCentralDirectory`] when an
    /// archive's central directory cannot be located.
    pub fn directories(&self) -> Result<Vec<ArchiveId<'_>>> {
        self.archives.iter().map(|a| Ok(ArchiveId { path: &a.path, label: &a.label, directory: a.directory()? })).collect()
    }

    /// A short name for the APK: the file stem, or for a program the first
    /// archive's and how many others follow.
    pub fn stem(&self) -> String {
        let first = self.archives[0].path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
        match self.archives.len() {
            1 => first,
            n => format!("{first}-and-{}", n - 1),
        }
    }

    /// `(size, modification time)` of the file; for a program, its sizes and
    /// times hashed into one number and the latest time, so rewriting any
    /// archive changes it.
    ///
    /// # Errors
    ///
    /// [`ApkError::Io`] when a file's metadata cannot be read.
    pub fn stamp(&self) -> Result<(u64, Option<SystemTime>)> {
        let meta = |a: &Archive| std::fs::metadata(&a.path).map_err(|source| ApkError::Io { path: a.path.clone(), source });
        if let [lone] = &self.archives[..] {
            let m = meta(lone)?;
            return Ok((m.len(), m.modified().ok()));
        }
        let mut size = 0u64;
        let mut latest = None;
        for a in self.archives.iter() {
            let m = meta(a)?;
            let since = m.modified().ok().and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok());
            // Only a hash input: the low bits of the nanoseconds are what differ.
            let nanos = since.map_or(0, |d| d.as_nanos() as u64);
            size = size.rotate_left(13) ^ m.len().wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ nanos;
            latest = latest.max(m.modified().ok());
        }
        Ok((size, latest))
    }

    /// Walk the central directories. `keep` filters entries by their name
    /// inside their archive early, so the full name list is never
    /// materialised for large archives.
    ///
    /// # Errors
    ///
    /// As [`Apk::directories`].
    pub fn entries_filtered(&self, mut keep: impl FnMut(&[u8]) -> bool) -> Result<Vec<Entry>> {
        let mut entries = Vec::new();
        for (i, a) in self.archives.iter().enumerate() {
            entries.extend(a.entries_filtered(i, &mut keep)?);
        }
        Ok(entries)
    }

    /// Every entry of the archive.
    ///
    /// # Errors
    ///
    /// As [`Apk::directories`].
    pub fn entries(&self) -> Result<Vec<Entry>> {
        self.entries_filtered(|_| true)
    }

    /// Root-level DEX entries sorted by compressed size (smallest first, so a
    /// parallel scan finishes the cheap ones early). Duplicate names keep the
    /// last occurrence, like [`Apk::find_entry`] (and `zipfile`).
    ///
    /// # Errors
    ///
    /// As [`Apk::directories`], and [`ApkError::LimitExceeded`] when the
    /// entries together declare more than [`Limits::max_dex_total_bytes`].
    pub fn dex_entries(&self) -> Result<Vec<Entry>> {
        let mut entries = self.dex_entries_in_order()?;
        self.check_dex_total(&entries)?;
        entries.sort_by_key(|e| e.comp_size);
        Ok(entries)
    }

    /// The entries of [`Apk::dex_entries`] in central-directory order, archive
    /// by archive. Unlike [`Apk::dex_entries`], the total size is not checked.
    ///
    /// # Errors
    ///
    /// As [`Apk::directories`].
    pub fn dex_entries_in_order(&self) -> Result<Vec<Entry>> {
        let mut entries = Vec::new();
        for (i, a) in self.archives.iter().enumerate() {
            entries.extend(a.dex_entries_in_order(i)?);
        }
        Ok(entries)
    }

    /// The entries of [`Apk::dex_entries`] in the order the runtime loads
    /// them, archive by archive: `classes.dex`, `classes2.dex`,
    /// `classes3.dex`, ... by number, then any other root `*.dex` in
    /// central-directory order. Duplicate names keep the last occurrence.
    ///
    /// # Errors
    ///
    /// As [`Apk::dex_entries`].
    pub fn dex_entries_multidex(&self) -> Result<Vec<Entry>> {
        let mut entries = self.dex_entries_in_order()?;
        self.check_dex_total(&entries)?;
        // Stable: entries outside the classesN.dex scheme keep their order.
        entries.sort_by_key(|e| (e.archive, multidex_rank(&e.name)));
        Ok(entries)
    }

    /// Every `*.dex` entry at any depth (`assets/payload.dex`,
    /// `lib/x/classes.dex` as well as the root ones), in central-directory
    /// order, archive by archive. Duplicate names keep the last occurrence.
    /// The runtime loads only the root entries ([`Apk::dex_entries`]); this
    /// is for callers that look at embedded code too. The total size is not
    /// checked. A program of several archives has already left out those
    /// without root DEX entries ([`Apk::open`]).
    ///
    /// # Errors
    ///
    /// As [`Apk::directories`].
    pub fn all_dex_entries(&self) -> Result<Vec<Entry>> {
        let mut entries = Vec::new();
        for (i, a) in self.archives.iter().enumerate() {
            entries.extend(a.dex_entries_matching(i, is_any_dex)?);
        }
        Ok(entries)
    }

    fn check_dex_total(&self, entries: &[Entry]) -> Result<()> {
        let total = entries.iter().fold(0u64, |t, e| t.saturating_add(e.uncomp_size));
        if total > self.limits.max_dex_total_bytes {
            return Err(ApkError::LimitExceeded {
                name: "classes*.dex".into(),
                reason: format!("DEX entries declare {total} bytes in all, limit {}", self.limits.max_dex_total_bytes),
            });
        }
        Ok(())
    }

    /// Find an entry by exact name. In a program, a name without an
    /// archive's prefix (`AndroidManifest.xml`) is looked up archive by
    /// archive, the first that has it winning.
    ///
    /// # Errors
    ///
    /// As [`Apk::directories`].
    pub fn find_entry(&self, name: &str) -> Result<Option<Entry>> {
        let owner = self.archives.iter().enumerate().find_map(|(i, a)| Some((i, a.inner_name(name)?)));
        let candidates: Vec<(usize, &str)> = match owner {
            Some(found) => vec![found],
            None => (0..self.archives.len()).map(|i| (i, name)).collect(),
        };
        for (i, inner) in candidates {
            let mut found = self.archives[i].entries_filtered(i, &mut |n: &[u8]| n == inner.as_bytes())?;
            if let Some(e) = found.pop() {
                return Ok(Some(e));
            }
        }
        Ok(None)
    }

    /// Compressed payload of `entry` inside the mapping.
    ///
    /// # Errors
    ///
    /// [`ApkError::BadLocalHeader`] when the local header is missing or the
    /// payload runs past the end of the archive.
    pub fn raw_payload(&self, entry: &Entry) -> Result<&[u8]> {
        let range = self.payload_range(entry)?;
        Ok(&self.archive(entry).map[range])
    }

    /// Where [`Apk::raw_payload`] of `entry` lies in its archive's bytes.
    fn payload_range(&self, entry: &Entry) -> Result<std::ops::Range<usize>> {
        let archive = self.archive(entry);
        let data = &archive.map[..];
        let bad = || ApkError::BadLocalHeader(entry.name.clone());
        if archive.bare_dex {
            return offset(entry.comp_size).filter(|&n| n <= data.len()).map(|n| 0..n).ok_or_else(bad);
        }
        let lh = offset(entry.local_header_off).ok_or_else(bad)?;
        if bytes_at(data, lh, 4) != Some(LH_SIG) {
            return Err(bad());
        }
        // The signature check bounds `lh`, so these small additions cannot overflow.
        let name_len = u16_at(data, lh + 26).ok_or_else(bad)? as usize;
        let extra_len = u16_at(data, lh + 28).ok_or_else(bad)? as usize;
        let start = lh + 30 + name_len + extra_len;
        let end = offset(entry.comp_size).and_then(|n| start.checked_add(n));
        end.filter(|&end| start <= end && end <= data.len()).map(|end| start..end).ok_or_else(bad)
    }

    /// The raw bytes of a lone archive's file (a zip, or a file that is not
    /// one, which a caller may know how to read); `None` for a program of
    /// several archives.
    pub fn lone_data(&self) -> Option<&[u8]> {
        match &self.archives[..] {
            [lone] => Some(&lone.map),
            _ => None,
        }
    }

    /// Bytes of the archives this holds on the heap: the inflated ones of
    /// [`Apk::open_nested`]. Clones share them.
    pub fn owned_bytes(&self) -> usize {
        self.archives.iter().map(|archive| if let Data::Owned(bytes) = &archive.map { bytes.capacity() } else { 0 }).sum()
    }

    /// Open `entry`, an archive inside this one (a `.hap` of an `.app`, a jar
    /// of a zip), as an archive of its own with this one's limits. A stored
    /// entry is read in place; a Deflate entry is inflated into memory and
    /// kept there for as long as the returned [`Apk`] lives. Its entry names
    /// are the names inside it.
    ///
    /// # Errors
    ///
    /// As [`Apk::read_entry`].
    pub fn open_nested(&self, entry: &Entry) -> Result<Apk> {
        let EntryBytes(map) = self.read_entry_owned(entry)?;
        let bare_dex = map.starts_with(b"dex\n");
        let nested = Archive { path: self.archive(entry).path.clone(), map, label: String::new(), bare_dex };
        Ok(Apk {
            path: self.path.clone(),
            archives: Arc::new([nested]),
            limits: self.limits,
            notes: Arc::new([]),
            version: self.version.clone(),
        })
    }

    /// Where the bytes of `entry` lie in [`Apk::archive_data`] when it is
    /// stored: `archive_data(entry)[range]` is what [`Apk::read_entry`]
    /// borrows. `None` for a compressed entry, which has to be inflated.
    /// With the range, a caller holding a clone of this [`Apk`] can keep a
    /// zero-copy view of the entry for as long as it likes (or see
    /// [`Apk::read_entry_owned`]).
    ///
    /// # Errors
    ///
    /// As [`Apk::read_entry`] for a stored entry: [`ApkError::BadLocalHeader`],
    /// [`ApkError::LimitExceeded`] and [`ApkError::SizeMismatch`].
    pub fn entry_range(&self, entry: &Entry) -> Result<Option<std::ops::Range<usize>>> {
        if entry.method != METHOD_STORED {
            return Ok(None);
        }
        let range = self.payload_range(entry)?;
        self.check_declared_size(entry)?;
        self.check_stored_size(entry, range.len())?;
        Ok(Some(range))
    }

    /// Extract `entry` into a handle that keeps its bytes alive on its own:
    /// a stored entry stays in the mapping (the handle shares it, like a
    /// clone of this [`Apk`]), a Deflate entry is inflated into the handle.
    ///
    /// # Errors
    ///
    /// As [`Apk::read_entry`].
    pub fn read_entry_owned(&self, entry: &Entry) -> Result<EntryBytes> {
        let data = match self.entry_range(entry)? {
            Some(range) => Data::Window { outer: Arc::clone(&self.archives), archive: entry.archive, range },
            None => Data::Owned(self.read_entry(entry)?.into_owned()),
        };
        Ok(EntryBytes(data))
    }

    /// Extract `entry`: stored entries are borrowed straight from the mapping,
    /// Deflate entries are inflated into a fresh buffer.
    ///
    /// # Errors
    ///
    /// As [`Apk::read_entry_cancellable`], except [`ApkError::Cancelled`].
    pub fn read_entry(&self, entry: &Entry) -> Result<Cow<'_, [u8]>> {
        self.read_entry_cancellable(entry, None)
    }

    /// Extract `entry`, polling `cancel` between input chunks. Returns
    /// `Err(ApkError::Cancelled)` when the flag is raised mid-way.
    ///
    /// # Errors
    ///
    /// [`ApkError::Cancelled`]; [`ApkError::BadLocalHeader`] when the payload
    /// cannot be located; [`ApkError::ImplausibleSize`] or
    /// [`ApkError::LimitExceeded`] when the declared or inflated size is out of
    /// bounds; [`ApkError::Inflate`] for a corrupt stream;
    /// [`ApkError::UnsupportedMethod`]; [`ApkError::SizeMismatch`] when the
    /// data is not the declared size.
    pub fn read_entry_cancellable(&self, entry: &Entry, cancel: Option<&AtomicBool>) -> Result<Cow<'_, [u8]>> {
        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
            return Err(ApkError::Cancelled);
        }
        let payload = self.raw_payload(entry)?;
        let bound = self.check_declared_size(entry)?;
        let out = match entry.method {
            METHOD_STORED => {
                self.check_stored_size(entry, payload.len())?;
                return Ok(Cow::Borrowed(payload));
            }
            #[cfg(feature = "libdeflate")]
            METHOD_DEFLATE if entry.uncomp_size > 0 => {
                if let Some(c) = cancel
                    && c.load(Ordering::Relaxed)
                {
                    return Err(ApkError::Cancelled);
                }
                let mut out = vec![0u8; entry.uncomp_size as usize];
                let n = libdeflater::Decompressor::new()
                    .deflate_decompress(payload, &mut out)
                    .map_err(|e| ApkError::Inflate { name: entry.name.clone(), source: std::io::Error::other(format!("{e:?}")) })?;
                out.truncate(n);
                out
            }
            METHOD_DEFLATE => {
                let reader = CancelReader { data: payload, pos: 0, cancel };
                let decoder = flate2::read::DeflateDecoder::new(reader);
                let reserve = (entry.uncomp_size as usize).min(INITIAL_CAPACITY.max(payload.len().saturating_mul(TYPICAL_RATIO)));
                let mut out = Vec::with_capacity(reserve);
                // Stop one byte past the bound so an over-long stream is detected
                // instead of inflated without limit (an entry that declares no
                // uncompressed size has no other cap).
                match decoder.take(bound.saturating_add(1)).read_to_end(&mut out) {
                    Ok(_) => {}
                    Err(_) if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) => return Err(ApkError::Cancelled),
                    Err(e) => return Err(ApkError::Inflate { name: entry.name.clone(), source: e }),
                }
                if out.len() as u64 > bound {
                    return Err(self.past_bound(entry, bound));
                }
                out
            }
            m => return Err(ApkError::UnsupportedMethod(m)),
        };
        if let Some(c) = cancel
            && c.load(Ordering::Relaxed)
        {
            return Err(ApkError::Cancelled);
        }
        if entry.uncomp_size != 0 && out.len() as u64 != entry.uncomp_size {
            return Err(ApkError::SizeMismatch { name: entry.name.clone(), expected: entry.uncomp_size as usize, actual: out.len() });
        }
        Ok(Cow::Owned(out))
    }

    /// A stored entry's payload must be as long as it declares (when it
    /// declares a size at all).
    fn check_stored_size(&self, entry: &Entry, len: usize) -> Result<()> {
        if entry.uncomp_size != 0 && len as u64 != entry.uncomp_size {
            return Err(ApkError::SizeMismatch { name: entry.name.clone(), expected: entry.uncomp_size as usize, actual: len });
        }
        Ok(())
    }

    /// Reject Deflate entries whose declared uncompressed size cannot come out
    /// of their compressed payload, before anything is allocated for them.
    /// Returns the most an inflated entry may legitimately grow to; it also
    /// bounds entries that declare no uncompressed size at all.
    fn check_declared_size(&self, entry: &Entry) -> Result<u64> {
        let bound = entry.comp_size.saturating_mul(MAX_DEFLATE_RATIO).saturating_add(1024);
        if entry.method == METHOD_DEFLATE && entry.uncomp_size > bound {
            return Err(self.implausible(entry));
        }
        let Limits { max_entry_bytes, max_ratio, .. } = self.limits;
        if entry.uncomp_size > max_entry_bytes {
            return Err(self.over_limit(entry, format!("declares {} bytes, limit {max_entry_bytes}", entry.uncomp_size)));
        }
        let ratio_bound = entry.comp_size.saturating_mul(max_ratio).saturating_add(1024);
        if entry.method == METHOD_DEFLATE && entry.uncomp_size > ratio_bound {
            return Err(self.over_limit(
                entry,
                format!("declares {} bytes from {} compressed, ratio limit {max_ratio}", entry.uncomp_size, entry.comp_size),
            ));
        }
        Ok(bound.min(ratio_bound).min(max_entry_bytes))
    }

    /// An entry whose stream ran past `bound` (from [`Apk::check_declared_size`]).
    fn past_bound(&self, entry: &Entry, bound: u64) -> ApkError {
        if bound < entry.comp_size.saturating_mul(MAX_DEFLATE_RATIO).saturating_add(1024) {
            self.over_limit(entry, format!("inflates past {bound} bytes"))
        } else {
            self.implausible(entry)
        }
    }

    fn over_limit(&self, entry: &Entry, reason: String) -> ApkError {
        ApkError::LimitExceeded { name: entry.name.clone(), reason }
    }

    fn implausible(&self, entry: &Entry) -> ApkError {
        ApkError::ImplausibleSize { name: entry.name.clone(), comp_size: entry.comp_size, uncomp_size: entry.uncomp_size }
    }

    /// Convenience: extract a named entry.
    ///
    /// # Errors
    ///
    /// [`ApkError::NotFound`] when there is no such entry, otherwise as
    /// [`Apk::find_entry`] and [`Apk::read_entry`].
    pub fn read(&self, name: &str) -> Result<Vec<u8>> {
        let entry = self.find_entry(name)?.ok_or_else(|| ApkError::NotFound(name.to_string()))?;
        Ok(self.read_entry(&entry)?.into_owned())
    }
}

/// The bytes of one entry, kept alive on their own ([`Apk::read_entry_owned`]):
/// a window of the shared mapping for a stored entry, a buffer for an
/// inflated one. Dereferences to the bytes.
pub struct EntryBytes(Data);

impl EntryBytes {
    /// Whether the bytes are read in place from an archive rather than held
    /// in a buffer of their own.
    pub fn is_mapped(&self) -> bool {
        matches!(self.0, Data::Window { .. })
    }
}

impl std::ops::Deref for EntryBytes {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        &self.0
    }
}

impl AsRef<[u8]> for EntryBytes {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl std::fmt::Debug for EntryBytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EntryBytes").field("len", &self.len()).field("mapped", &self.is_mapped()).finish()
    }
}

/// Decision returned by the callback of [`Apk::inflate_until`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrefixStep {
    /// Keep inflating; stop once at least this many bytes are available
    /// (`0` = undecided, ask again after the next chunk).
    Continue(usize),
    /// A prefix is not useful for this entry; stop now.
    Abort,
}

/// Outcome of [`Apk::inflate_until`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Prefix {
    /// The whole entry (the stream ended before or at the requested length).
    Complete(Vec<u8>),
    /// At least the requested number of leading bytes.
    Partial(Vec<u8>),
    /// The callback aborted; holds whatever was inflated so far.
    Aborted(Vec<u8>),
}

impl Apk {
    /// Inflate a Deflate entry incrementally, letting `decide` inspect the
    /// leading bytes after every chunk to say how much of the entry is
    /// actually needed. Stored entries are returned whole.
    ///
    /// # Errors
    ///
    /// As [`Apk::read_entry`]: a payload that cannot be located, a size out
    /// of bounds, or a corrupt stream.
    pub fn inflate_until(&self, entry: &Entry, mut decide: impl FnMut(&[u8]) -> PrefixStep) -> Result<Prefix> {
        // Small first chunks so a quick "not useful" costs little; then up to CHUNK.
        const FIRST_CHUNK: usize = 1 << 14;
        const CHUNK: usize = 1 << 18;
        let mut chunk = FIRST_CHUNK;
        if entry.method != METHOD_DEFLATE {
            return Ok(Prefix::Complete(self.read_entry(entry)?.into_owned()));
        }
        let compressed = self.raw_payload(entry)?;
        let bound = self.check_declared_size(entry)?;
        let mut d = flate2::Decompress::new(false);
        let mut out: Vec<u8> = Vec::with_capacity((entry.uncomp_size as usize).min(4 * CHUNK));
        let mut target: Option<usize> = None;
        loop {
            if out.len() as u64 > bound {
                return Err(self.past_bound(entry, bound));
            }
            let base = out.len();
            out.resize(base + chunk, 0);
            chunk = (chunk * 2).min(CHUNK);
            let consumed = d.total_in() as usize;
            let status = d
                .decompress(&compressed[consumed.min(compressed.len())..], &mut out[base..], flate2::FlushDecompress::None)
                .map_err(|e| ApkError::Inflate { name: entry.name.clone(), source: std::io::Error::other(e) })?;
            let written = d.total_out() as usize - base;
            out.truncate(base + written);
            if target.is_none() {
                match decide(&out) {
                    PrefixStep::Continue(0) => {}
                    PrefixStep::Continue(limit) => {
                        // An entry that declares no size cannot cap the request.
                        target = Some(if entry.uncomp_size == 0 { limit } else { limit.min(entry.uncomp_size as usize) })
                    }
                    PrefixStep::Abort => return Ok(Prefix::Aborted(out)),
                }
            }
            if status == flate2::Status::StreamEnd {
                return Ok(Prefix::Complete(out));
            }
            if let Some(limit) = target
                && out.len() >= limit
            {
                return Ok(Prefix::Partial(out));
            }
            if written == 0 && d.total_in() as usize == consumed {
                return Err(ApkError::Inflate { name: entry.name.clone(), source: std::io::Error::other("deflate made no progress") });
            }
        }
    }
}

/// Slice reader that serves bounded chunks and honours a cancellation flag.
struct CancelReader<'a> {
    data: &'a [u8],
    pos: usize,
    cancel: Option<&'a AtomicBool>,
}

impl Read for CancelReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if let Some(c) = self.cancel
            && c.load(Ordering::Relaxed)
        {
            return Err(std::io::Error::other("cancelled"));
        }
        let remaining = &self.data[self.pos..];
        let n = remaining.len().min(buf.len()).min(DEFLATE_CHUNK);
        buf[..n].copy_from_slice(&remaining[..n]);
        self.pos += n;
        Ok(n)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn write_temp(bytes: &[u8]) -> tempfile::NamedTempFile {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(bytes).unwrap();
        f.flush().unwrap();
        f
    }

    #[test]
    fn limits_reject_bombs_before_inflating() {
        // Zeros compress far beyond any real DEX.
        let bomb = vec![0u8; 4 << 20];
        let f = write_temp(&asc_fixture::make_apk(&[("classes.dex", &bomb)], true));
        let apk = Apk::open(f.path()).unwrap();
        let entry = apk.dex_entries().unwrap().remove(0);
        assert_eq!(apk.read_entry(&entry).unwrap().len(), bomb.len());
        let apk = Apk::open(f.path()).unwrap().with_limits(Limits::guarded());
        let err = apk.read_entry(&entry).unwrap_err();
        assert!(matches!(&err, ApkError::LimitExceeded { reason, .. } if reason.contains("ratio limit 100")), "{err}");
        // An entry with no declared size is cut off by the same bound while streaming.
        let mut undeclared = entry.clone();
        undeclared.uncomp_size = 0;
        assert!(matches!(apk.read_entry(&undeclared), Err(ApkError::LimitExceeded { .. })));
        let small = Limits { max_entry_bytes: 1 << 20, ..Limits::default() };
        let apk = Apk::open(f.path()).unwrap().with_limits(small);
        assert!(matches!(apk.read_entry(&entry), Err(ApkError::LimitExceeded { .. })));
        let total = Limits { max_dex_total_bytes: 1 << 20, ..Limits::default() };
        let apk = Apk::open(f.path()).unwrap().with_limits(total);
        assert!(matches!(apk.dex_entries(), Err(ApkError::LimitExceeded { .. })));
    }

    #[test]
    fn enumerates_and_inflates_dex_entries() {
        let dex = asc_fixture::make_dex();
        for deflate in [false, true] {
            let apk_bytes = asc_fixture::make_apk(
                &[("classes.dex", &dex), ("lib/x/classes.dex", &dex), ("classes2.dex", &dex), ("AndroidManifest.xml", b"xml")],
                deflate,
            );
            let f = write_temp(&apk_bytes);
            let apk = Apk::open(f.path()).unwrap();
            let entries = apk.dex_entries().unwrap();
            let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
            assert_eq!(names.len(), 2);
            assert!(names.contains(&"classes.dex") && names.contains(&"classes2.dex"));
            for e in &entries {
                assert_eq!(apk.read_entry(e).unwrap().as_ref(), dex.as_slice());
            }
            assert_eq!(apk.read("AndroidManifest.xml").unwrap(), b"xml");
            let cancel = AtomicBool::new(true);
            let r = apk.read_entry_cancellable(&entries[0], Some(&cancel));
            assert!(matches!(r, Err(ApkError::Cancelled)));
            if deflate {
                // A lying central directory must not drive a huge allocation.
                let mut lying = entries[0].clone();
                lying.uncomp_size = 1 << 40;
                assert!(matches!(apk.read_entry(&lying), Err(ApkError::ImplausibleSize { .. })));
                assert!(matches!(apk.inflate_until(&lying, |_| PrefixStep::Continue(0)), Err(ApkError::ImplausibleSize { .. })));
                let mut truncated = entries[0].clone();
                truncated.comp_size = u64::MAX;
                assert!(matches!(apk.read_entry(&truncated), Err(ApkError::BadLocalHeader(_))));
            }
        }
    }

    #[test]
    fn entries_outlive_their_apk_in_place_or_inflated() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<EntryBytes>();
        let dex = asc_fixture::make_dex();
        for deflate in [false, true] {
            let f = write_temp(&asc_fixture::make_apk(&[("classes.dex", &dex), ("a.txt", b"text")], deflate));
            let apk = Apk::open(f.path()).unwrap();
            let entry = apk.find_entry("classes.dex").unwrap().unwrap();
            let range = apk.entry_range(&entry).unwrap();
            assert_eq!(range.is_some(), !deflate);
            if let Some(range) = &range {
                let Cow::Borrowed(read) = apk.read_entry(&entry).unwrap() else { panic!("a stored entry is borrowed") };
                assert_eq!(&apk.archive_data(&entry)[range.clone()], read);
                assert_eq!(apk.archive_data(&entry)[range.clone()].as_ptr(), read.as_ptr());
            }
            let owned = apk.read_entry_owned(&entry).unwrap();
            assert_eq!(owned.is_mapped(), !deflate);
            if let Some(range) = range {
                assert_eq!(owned.as_ptr(), apk.archive_data(&entry)[range].as_ptr());
            }
            drop(apk);
            assert_eq!(&*owned, dex.as_slice());
            assert_eq!(owned.as_ref(), dex.as_slice());
            assert!(format!("{owned:?}").contains(&format!("len: {}", dex.len())));
        }
        // A stored entry is checked like any read.
        let f = write_temp(&asc_fixture::make_apk(&[("classes.dex", &dex)], false));
        let apk = Apk::open(f.path()).unwrap();
        let mut lying = apk.find_entry("classes.dex").unwrap().unwrap();
        lying.uncomp_size += 1;
        assert!(matches!(apk.entry_range(&lying), Err(ApkError::SizeMismatch { .. })));
        assert!(matches!(apk.read_entry_owned(&lying), Err(ApkError::SizeMismatch { .. })));
        lying.local_header_off += 1;
        assert!(matches!(apk.entry_range(&lying), Err(ApkError::BadLocalHeader(_))));
        let small = apk.clone().with_limits(Limits::default().max_entry_bytes(16));
        let entry = small.find_entry("classes.dex").unwrap().unwrap();
        assert!(matches!(small.entry_range(&entry), Err(ApkError::LimitExceeded { .. })));
    }

    #[test]
    fn all_dex_entries_reach_any_depth() {
        let dex = asc_fixture::make_dex();
        let apk_bytes = asc_fixture::make_apk(
            &[
                ("classes2.dex", &dex),
                ("assets/payload.dex", b"x"),
                ("classes.dex", &dex),
                ("lib/x/classes.dex", &dex),
                ("assets/notdex.dex.bak", b"y"),
                ("AndroidManifest.xml", b"xml"),
            ],
            true,
        );
        let f = write_temp(&apk_bytes);
        let apk = Apk::open(f.path()).unwrap();
        let names = |entries: Vec<Entry>| entries.into_iter().map(|e| e.name).collect::<Vec<_>>();
        assert_eq!(names(apk.all_dex_entries().unwrap()), ["classes2.dex", "assets/payload.dex", "classes.dex", "lib/x/classes.dex"]);
        // The root enumeration is unchanged.
        assert_eq!(names(apk.dex_entries_in_order().unwrap()), ["classes2.dex", "classes.dex"]);
        let payload = apk.all_dex_entries().unwrap().remove(1);
        assert_eq!(apk.read_entry(&payload).unwrap().as_ref(), b"x");
        // A bare DEX file is its one entry.
        let f = write_temp(&dex);
        assert_eq!(names(Apk::open(f.path()).unwrap().all_dex_entries().unwrap()), ["classes.dex"]);
    }

    #[test]
    fn multidex_entries_follow_the_runtime_load_order() {
        let dex = asc_fixture::make_dex();
        let apk_bytes = asc_fixture::make_apk(
            &[
                ("classes10.dex", &dex),
                ("extra.dex", &dex),
                ("classes2.dex", &dex),
                ("classes.dex", &dex),
                ("classes02.dex", &dex),
                ("classes3.dex", &dex),
                ("assets/classes4.dex", &dex),
            ],
            true,
        );
        let f = write_temp(&apk_bytes);
        let apk = Apk::open(f.path()).unwrap();
        let names: Vec<String> = apk.dex_entries_multidex().unwrap().into_iter().map(|e| e.name).collect();
        assert_eq!(names, ["classes.dex", "classes2.dex", "classes3.dex", "classes10.dex", "extra.dex", "classes02.dex"]);
        assert_eq!(multidex_rank("services.jar/classes2.dex"), 2);
    }

    /// Deflate stream of `n` zero bytes (compresses about 1000:1).
    fn zeros_deflated(n: usize) -> Vec<u8> {
        let mut e = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::best());
        e.write_all(&vec![0u8; n]).unwrap();
        e.finish().unwrap()
    }

    /// Hand-rolled zip (the `zip` crate refuses duplicate names and always
    /// writes true sizes): `(name, method, payload, comp_size, uncomp_size)`.
    fn raw_zip(entries: &[(&str, u16, &[u8], u32, u32)]) -> Vec<u8> {
        let mut z = Vec::new();
        let mut cd = Vec::new();
        for (name, method, payload, comp_size, uncomp_size) in entries {
            let lh = z.len() as u32;
            z.extend_from_slice(LH_SIG);
            z.extend_from_slice(&[20, 0, 0, 0]);
            z.extend_from_slice(&method.to_le_bytes());
            z.extend_from_slice(&[0; 8]);
            z.extend_from_slice(&comp_size.to_le_bytes());
            z.extend_from_slice(&uncomp_size.to_le_bytes());
            z.extend_from_slice(&(name.len() as u16).to_le_bytes());
            z.extend_from_slice(&0u16.to_le_bytes());
            z.extend_from_slice(name.as_bytes());
            z.extend_from_slice(payload);
            cd.extend_from_slice(CD_SIG);
            cd.extend_from_slice(&[20, 0, 20, 0, 0, 0]);
            cd.extend_from_slice(&method.to_le_bytes());
            cd.extend_from_slice(&[0; 8]);
            cd.extend_from_slice(&comp_size.to_le_bytes());
            cd.extend_from_slice(&uncomp_size.to_le_bytes());
            cd.extend_from_slice(&(name.len() as u16).to_le_bytes());
            cd.extend_from_slice(&[0; 12]);
            cd.extend_from_slice(&lh.to_le_bytes());
            cd.extend_from_slice(name.as_bytes());
        }
        let cd_off = z.len() as u32;
        z.extend_from_slice(&cd);
        z.extend_from_slice(EOCD_SIG);
        z.extend_from_slice(&[0, 0, 0, 0]);
        z.extend_from_slice(&(entries.len() as u16).to_le_bytes());
        z.extend_from_slice(&(entries.len() as u16).to_le_bytes());
        z.extend_from_slice(&(cd.len() as u32).to_le_bytes());
        z.extend_from_slice(&cd_off.to_le_bytes());
        z.extend_from_slice(&[0, 0]);
        z
    }

    #[test]
    fn undeclared_size_is_still_bounded() {
        // 1 MiB of zeros deflates to about 1 KiB; the 1032:1 bound allows it.
        let ok = zeros_deflated(1 << 20);
        let f = write_temp(&raw_zip(&[("classes.dex", METHOD_DEFLATE, &ok, ok.len() as u32, 0)]));
        let apk = Apk::open(f.path()).unwrap();
        let e = apk.dex_entries().unwrap().remove(0);
        assert_eq!(e.uncomp_size, 0);
        assert_eq!(apk.read_entry(&e).unwrap().len(), 1 << 20);
        match apk.inflate_until(&e, |_| PrefixStep::Continue(4096)).unwrap() {
            Prefix::Partial(v) => assert!(v.len() >= 4096),
            Prefix::Complete(v) => assert_eq!(v.len(), 1 << 20),
            Prefix::Aborted(_) => panic!("unexpected abort"),
        }
        // A shorter compressed size lowers the bound and truncates the stream:
        // either way the entry is rejected instead of inflated open-endedly.
        let mut lying = e.clone();
        lying.comp_size = 200;
        assert!(apk.read_entry(&lying).is_err());
        assert!(apk.inflate_until(&lying, |_| PrefixStep::Continue(0)).is_err());
    }

    #[test]
    fn hostile_offsets_do_not_overflow() {
        let dex = asc_fixture::make_dex();
        let f = write_temp(&asc_fixture::make_apk(&[("classes.dex", &dex)], true));
        let apk = Apk::open(f.path()).unwrap();
        let mut e = apk.dex_entries().unwrap().remove(0);
        for off in [u64::MAX, u64::MAX - 3, u64::MAX - 40, u32::MAX as u64] {
            e.local_header_off = off;
            assert!(matches!(apk.read_entry(&e), Err(ApkError::BadLocalHeader(_))));
            assert!(matches!(apk.inflate_until(&e, |_| PrefixStep::Continue(0)), Err(ApkError::BadLocalHeader(_))));
        }
        // zip64 locator pointing at an offset near usize::MAX.
        let mut bytes = asc_fixture::make_apk(&[("classes.dex", &dex)], false);
        let eocd = bytes.len() - 22;
        bytes[eocd + 16..eocd + 20].copy_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
        let mut locator = Vec::new();
        locator.extend_from_slice(ZIP64_LOCATOR_SIG);
        locator.extend_from_slice(&0u32.to_le_bytes());
        locator.extend_from_slice(&(u64::MAX - 2).to_le_bytes());
        locator.extend_from_slice(&1u32.to_le_bytes());
        let tail = bytes.split_off(eocd);
        bytes.extend_from_slice(&locator);
        bytes.extend_from_slice(&tail);
        let f = write_temp(&bytes);
        let apk = Apk::open(f.path()).unwrap();
        assert!(matches!(apk.dex_entries(), Err(ApkError::NoEocd | ApkError::BadCentralDirectory)));
    }

    #[test]
    fn duplicate_root_dex_names_keep_the_last() {
        let a = asc_fixture::make_dex();
        let mut b = a.clone();
        b.push(0); // different content, same name
        let (la, lb) = (a.len() as u32, b.len() as u32);
        let f = write_temp(&raw_zip(&[
            ("classes.dex", METHOD_STORED, &a, la, la),
            ("classes2.dex", METHOD_STORED, &a, la, la),
            ("classes.dex", METHOD_STORED, &b, lb, lb),
        ]));
        let apk = Apk::open(f.path()).unwrap();
        let entries = apk.dex_entries().unwrap();
        let mut names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
        names.sort();
        assert_eq!(names, ["classes.dex", "classes2.dex"]);
        let dup = entries.iter().find(|e| e.name == "classes.dex").unwrap();
        assert_eq!(apk.read_entry(dup).unwrap().as_ref(), b.as_slice());
        assert_eq!(apk.find_entry("classes.dex").unwrap().unwrap(), *dup);
        // Central-directory order, the duplicate at its last position.
        let ordered: Vec<String> = apk.dex_entries_in_order().unwrap().into_iter().map(|e| e.name).collect();
        assert_eq!(ordered, ["classes2.dex", "classes.dex"]);
    }

    #[test]
    fn programs_name_entries_after_their_archive() {
        let dex = asc_fixture::make_dex();
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("system");
        std::fs::create_dir_all(root.join("app/Tele")).unwrap();
        let both = [("classes.dex", &dex[..]), ("classes2.dex", &dex[..]), ("AndroidManifest.xml", b"first")];
        std::fs::write(root.join("services.jar"), asc_fixture::make_apk(&both, true)).unwrap();
        let apk = [("classes.dex", &dex[..]), ("AndroidManifest.xml", b"second")];
        std::fs::write(root.join("app/Tele/Tele.apk"), asc_fixture::make_apk(&apk, false)).unwrap();
        std::fs::write(root.join("odexed.jar"), asc_fixture::make_apk(&[("META-INF/MANIFEST.MF", b"m")], false)).unwrap();
        std::fs::write(root.join("bare.dex"), &dex).unwrap();
        std::fs::write(root.join("broken.zip"), b"not a zip").unwrap();

        let program = Apk::open(&root).unwrap();
        assert_eq!(program.archive_count(), 3);
        let names: Vec<String> = program.dex_entries_in_order().unwrap().into_iter().map(|e| e.name).collect();
        assert_eq!(
            names,
            ["app/Tele/Tele.apk/classes.dex", "bare.dex/classes.dex", "services.jar/classes.dex", "services.jar/classes2.dex"]
        );
        for e in program.dex_entries().unwrap() {
            assert_eq!(program.read_entry(&e).unwrap().as_ref(), dex.as_slice(), "{}", e.name);
        }
        let notes = program.notes().join("\n");
        assert!(notes.contains("broken.zip") && notes.contains("odexed.jar: no classes*.dex"), "{notes}");
        // Unprefixed names: the first archive that has one; prefixed: that archive's.
        assert_eq!(program.read("AndroidManifest.xml").unwrap(), b"second");
        assert_eq!(program.read("services.jar/AndroidManifest.xml").unwrap(), b"first");
        let bare = program.find_entry("bare.dex/classes.dex").unwrap().unwrap();
        assert_eq!(program.archive_path(&bare), root.join("bare.dex"));
        assert_eq!(archive_of("app/Tele/Tele.apk/classes.dex"), Some("app/Tele/Tele.apk"));
        assert_eq!(archive_of("services.jar/classes5.dex!classes1.dex"), Some("services.jar"));
        assert_eq!(archive_of("classes5.dex!classes1.dex"), None);
        assert_eq!(program.stem(), "Tele-and-2");
        assert!(program.stamp().is_ok() && program.directories().unwrap().len() == 3);

        // A lone bare DEX, and a list that comes down to one archive, read as before.
        let lone = Apk::open(root.join("bare.dex")).unwrap();
        assert_eq!(lone.dex_entries().unwrap()[0].name, "classes.dex");
        let spec = format!("{},{}", root.join("services.jar").display(), root.join("odexed.jar").display());
        let one = Apk::open(&spec).unwrap();
        assert_eq!(one.archive_count(), 1);
        assert_eq!(one.dex_entries_in_order().unwrap()[0].name, "classes.dex");
        assert_eq!(one.notes().len(), 1);
        let spec = format!("{},{}", root.join("odexed.jar").display(), root.join("broken.zip").display());
        assert!(matches!(Apk::open(&spec), Err(ApkError::NoCode { .. })));
    }

    #[test]
    fn inflate_until_streams_prefixes() {
        let dex = asc_fixture::make_dex();
        let apk_bytes = asc_fixture::make_apk(&[("classes.dex", &dex)], true);
        let f = write_temp(&apk_bytes);
        let apk = Apk::open(f.path()).unwrap();
        let entry = apk.dex_entries().unwrap().remove(0);
        match apk.inflate_until(&entry, |_| PrefixStep::Continue(8)).unwrap() {
            Prefix::Complete(v) | Prefix::Partial(v) => assert!(v.starts_with(b"dex\n") && v.len() >= 8),
            Prefix::Aborted(_) => panic!("unexpected abort"),
        }
        assert!(matches!(apk.inflate_until(&entry, |_| PrefixStep::Abort).unwrap(), Prefix::Aborted(_)));
    }

    #[test]
    fn nested_archives_open_in_place_or_inflated() {
        let inner = asc_fixture::make_apk(&[("ets/modules.abc", b"PANDA body"), ("module.json", b"{}")], false);
        for deflate in [false, true] {
            let file = write_temp(&asc_fixture::make_apk(&[("entry.hap", &inner), ("pack.info", b"{}")], deflate));
            let outer = Apk::open(file.path()).unwrap();
            assert!(outer.lone_data().is_some_and(|data| data.starts_with(LH_SIG)));
            let entry = outer.find_entry("entry.hap").unwrap().unwrap();
            assert_eq!(entry.method, if deflate { METHOD_DEFLATE } else { METHOD_STORED });
            let nested = outer.open_nested(&entry).unwrap();
            assert_eq!(nested.lone_data(), Some(&inner[..]));
            // A stored inner archive is a window on the outer mapping, not a copy.
            let outer_range = outer.lone_data().unwrap().as_ptr_range();
            assert_eq!(outer_range.contains(&nested.lone_data().unwrap().as_ptr()), !deflate);
            let names: Vec<String> = nested.entries().unwrap().into_iter().map(|e| e.name).collect();
            assert_eq!(names, ["ets/modules.abc", "module.json"]);
            let abc = nested.find_entry("ets/modules.abc").unwrap().unwrap();
            assert!(matches!(nested.read_entry(&abc).unwrap(), Cow::Borrowed(b"PANDA body")));
            // The nested archive keeps the outer bytes alive on its own.
            drop(outer);
            assert_eq!(nested.read("module.json").unwrap(), b"{}");
        }
        let not_zip = write_temp(&asc_fixture::make_apk(&[("x.hap", b"not a zip")], false));
        let outer = Apk::open(not_zip.path()).unwrap();
        let nested = outer.open_nested(&outer.find_entry("x.hap").unwrap().unwrap()).unwrap();
        assert!(matches!(nested.entries(), Err(ApkError::NoEocd)));
    }
}