frostbite-formats 0.3.0

Read and write the Frostbite containers and resources of skate. (2025): TOCs, bundles, CAS, EBX documents, shaders, meshes, physics, .fbmod mods
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
//! Decoding an EBX document from its bytes (ReSkate `ebx_document.cpp`, `read_document`).
use std::collections::BTreeMap;

use super::{
    ArrayRecord, BoxedRef, BoxedValueRecord, Document, FieldDescriptor, FieldType, FieldValue,
    ImportReference, Instance, Object, Pointer, ReflectionGroup, TypeDescriptor, TypeRef, Value,
};
use crate::{Result, bad};
use primase_foundations::bytes::Endian;

const RIFF: u32 = 0x4646_4952; // "RIFF" read little-endian
const EBX: u32 = 0x4542_5800;
const EBXS: u32 = 0x4542_5853;
const EBXD: u32 = 0x4542_5844;
const EFIX: u32 = 0x4546_4958;
const EBXX: u32 = 0x4542_5858;
const REFL: u32 = 0x5245_464C;
const RFL2: u32 = 0x5246_4C32;

/// How deep types may nest (a type naming itself as its base or member fails instead of recursing forever).
const MAX_DEPTH: u32 = 128;

/// The 32-bit float with bits `bits` as an `f64`. A NaN widens by moving its sign and shifting its payload, so a
/// signalling NaN stays signalling and [`narrow_f32`] gives the bits back; every other value converts exactly.
pub(super) fn widen_f32(bits: u32) -> f64 {
    let f = f32::from_bits(bits);
    if !f.is_nan() {
        return f64::from(f);
    }
    let sign = u64::from(bits >> 31) << 63;
    f64::from_bits(sign | 0x7FF0_0000_0000_0000 | (u64::from(bits & 0x007F_FFFF) << 29))
}

/// The bits of the 32-bit float an `f64` stands for: the inverse of [`widen_f32`] for a NaN (its top 23 payload bits;
/// a NaN whose payload is lost stays a NaN, quiet), the nearest `f32` otherwise.
#[allow(
    clippy::cast_possible_truncation,
    reason = "a finite value is rounded to the nearest f32 (callers refuse one beyond f32::MAX); a NaN's fields are masked to fit"
)]
pub(super) fn narrow_f32(x: f64) -> u32 {
    if !x.is_nan() {
        return (x as f32).to_bits();
    }
    let bits = x.to_bits();
    let payload = ((bits >> 29) & 0x007F_FFFF) as u32;
    let quiet = if payload == 0 { 0x0040_0000 } else { 0 };
    (((bits >> 63) as u32) << 31) | 0x7F80_0000 | payload | quiet
}

pub(crate) fn align_up(v: usize, a: usize) -> usize {
    if a <= 1 {
        v
    } else {
        v.div_ceil(a).saturating_mul(a)
    }
}

/// The data-relative form of the place `position` plus `displacement` names, after `data_start` is taken off (the key
/// the instance and array tables are indexed by); saturating, so a displacement that leaves the address space names no
/// entry.
fn data_relative(position: usize, displacement: i64, data_start: usize) -> i64 {
    i64::try_from(position)
        .unwrap_or(i64::MAX)
        .saturating_add(displacement)
        .saturating_sub(i64::try_from(data_start).unwrap_or(0))
}

/// The document's cursor ([`primase_foundations::bytes::Cursor`]), with its strings, counts and extents as methods.
struct Cursor<'a>(primase_foundations::bytes::Cursor<'a>);

impl<'a> std::ops::Deref for Cursor<'a> {
    type Target = primase_foundations::bytes::Cursor<'a>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for Cursor<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a> Cursor<'a> {
    fn new(d: &'a [u8]) -> Self {
        Cursor(primase_foundations::bytes::Cursor::new(d))
    }
    fn nonnegative(&mut self, what: &'static str) -> Result<usize> {
        let at = self.position();
        let v = self.i32(Endian::Little)?;
        usize::try_from(v).map_err(|_| bad(what, at, "count cannot be negative"))
    }
    /// That `count` records of `stride` bytes fit before `end`.
    fn ensure(&self, end: usize, count: usize, stride: usize, what: &'static str) -> Result<()> {
        let room = end
            .checked_sub(self.position())
            .and_then(|room| room.checked_div(stride));
        if room.is_none_or(|room| count > room) {
            return Err(bad(
                what,
                self.position(),
                format!("{count} records exceed their chunk"),
            ));
        }
        Ok(())
    }
    fn c_string(&mut self) -> Result<Vec<u8>> {
        let rest = self.bytes().get(self.position()..).unwrap_or_default();
        let mut parts = rest.splitn(2, |&b| b == 0);
        let (Some(text), Some(_)) = (parts.next(), parts.next()) else {
            return Err(bad(
                "string",
                self.position(),
                "unterminated, expected a zero byte",
            ));
        };
        let s = text.to_vec();
        self.take(s.len().saturating_add(1))?;
        Ok(s)
    }
}

#[derive(Clone, Copy)]
struct Chunk {
    id: u32,
    begin: usize,
    end: usize,
}

fn read_chunks(r: &mut Cursor) -> Result<Vec<Chunk>> {
    if r.u32(Endian::Little)? != RIFF {
        return Err(bad("RIFF", 0, "not a RIFF document"));
    }
    let riff_end = (r.u32(Endian::Little)? as usize).saturating_add(8);
    if riff_end != r.bytes().len() {
        return Err(bad(
            "RIFF",
            4,
            format!("size {riff_end} does not match the stream ({})", r.bytes().len()),
        ));
    }
    let form = r.u32(Endian::Big)?;
    if form != EBX && form != EBXS {
        return Err(bad("RIFF", 8, format!("form {form:#x} is not EBX or EBXS")));
    }
    let mut chunks = Vec::new();
    while r.position() < riff_end {
        if r.bytes().len().saturating_sub(r.position()) < 8 {
            return Err(bad("RIFF", r.position(), "truncated chunk header"));
        }
        let id = r.u32(Endian::Big)?;
        let size = r.u32(Endian::Little)? as usize;
        let begin = r.position();
        if riff_end.checked_sub(begin).is_none_or(|room| size > room) {
            return Err(bad("RIFF", begin, "chunk exceeds its document"));
        }
        let end = begin.saturating_add(size);
        chunks.push(Chunk { id, begin, end });
        let next = end.saturating_add(size & 1);
        if next > riff_end {
            return Err(bad("RIFF", end, "chunk padding is truncated"));
        }
        r.seek(next)?;
    }
    Ok(chunks)
}

fn one_chunk(chunks: &[Chunk], id: u32, name: &'static str, required: bool) -> Result<Option<Chunk>> {
    let mut found = None;
    for c in chunks.iter().filter(|c| c.id == id) {
        if found.is_some() {
            return Err(bad(name, c.begin, "duplicate chunk"));
        }
        found = Some(*c);
    }
    if required && found.is_none() {
        return Err(bad(name, 0, "missing chunk"));
    }
    Ok(found)
}

fn validate_data_offset(doc: &Document, offset: u32, required: usize, what: &'static str) -> Result<()> {
    let size = doc.data_end.saturating_sub(doc.data_start);
    let o = offset as usize;
    if o > size || required > size.saturating_sub(o) {
        return Err(bad(
            what,
            doc.data_start.saturating_add(o),
            format!("offset exceeds EBXD: expected {required} bytes at most {size} bytes into the data"),
        ));
    }
    Ok(())
}

fn read_fixup(r: &mut Cursor, c: Chunk, doc: &mut Document) -> Result<()> {
    r.seek(c.begin)?;
    doc.file_guid = r.array()?;
    let types = r.nonnegative("EFIX type")?;
    r.ensure(c.end, types, 16, "EFIX type")?;
    for _ in 0..types {
        doc.fixup_type_guids.push(r.array()?);
    }
    let sigs = r.nonnegative("EFIX signature")?;
    if sigs > types {
        return Err(bad("EFIX signature", r.position(), "more signatures than types"));
    }
    r.ensure(c.end, sigs, 4, "EFIX signature")?;
    for _ in 0..sigs {
        doc.fixup_type_signatures.push(r.u32(Endian::Little)?);
    }
    let exported = r.nonnegative("EFIX exported instance")?;
    let instances = r.nonnegative("EFIX instance")?;
    if exported > instances {
        return Err(bad(
            "EFIX instance",
            r.position(),
            "exported count exceeds the instances",
        ));
    }
    r.ensure(c.end, instances, 4, "EFIX instance")?;
    for i in 0..instances {
        let offset = r.u32(Endian::Little)?;
        validate_data_offset(doc, offset, 2, "EFIX instance")?;
        let at = doc.data_start.saturating_add(offset as usize);
        let class_ref = r
            .bytes()
            .get(at..)
            .and_then(|b| b.first_chunk::<2>())
            .map(|b| u16::from_le_bytes(*b))
            .ok_or_else(|| {
                bad(
                    "EFIX instance",
                    at,
                    "instance type slot past the end: expected 2 bytes",
                )
            })?;
        if usize::from(class_ref) >= doc.fixup_type_guids.len() {
            return Err(bad(
                "EFIX instance",
                at,
                format!("type slot {class_ref} is invalid"),
            ));
        }
        doc.instances.push(Instance {
            fixup_type: class_ref,
            descriptor: None,
            data_offset: offset,
            exported: i < exported,
            guid: [0; 16],
            object: None,
            raw_image: Vec::new(),
        });
    }
    let offsets = |r: &mut Cursor, doc: &Document, what: &'static str, width: usize| -> Result<Vec<u32>> {
        let n = r.nonnegative(what)?;
        r.ensure(c.end, n, 4, what)?;
        let mut out = Vec::with_capacity(n);
        for _ in 0..n {
            let o = r.u32(Endian::Little)?;
            validate_data_offset(doc, o, width, what)?;
            out.push(o);
        }
        Ok(out)
    };
    doc.pointer_offsets = offsets(r, doc, "EFIX pointer", 8)?;
    doc.resource_ref_offsets = offsets(r, doc, "EFIX resource reference", 8)?;
    let imports = r.nonnegative("EFIX import")?;
    r.ensure(c.end, imports, 32, "EFIX import")?;
    for _ in 0..imports {
        doc.imports.push(ImportReference {
            file_guid: r.array()?,
            class_guid: r.array()?,
        });
    }
    doc.import_offsets = offsets(r, doc, "EFIX import relocation", 8)?;
    doc.type_info_offsets = offsets(r, doc, "EFIX type-info reference", 8)?;
    if c.end.saturating_sub(r.position()) < 12 {
        return Err(bad("EFIX", r.position(), "truncated section offsets"));
    }
    doc.arrays_offset = r.u32(Endian::Little)?;
    doc.boxed_values_offset = r.u32(Endian::Little)?;
    doc.strings_offset = r.u32(Endian::Little)?;
    validate_data_offset(doc, doc.arrays_offset, 0, "EFIX array section")?;
    validate_data_offset(doc, doc.boxed_values_offset, 0, "EFIX boxed-value section")?;
    validate_data_offset(doc, doc.strings_offset, 0, "EFIX string section")?;
    if r.position() < c.end {
        doc.boxed_reference_offsets = offsets(r, doc, "EFIX boxed reference", 16)?;
    }
    if r.position() != c.end {
        return Err(bad("EFIX", r.position(), "unexpected bytes at its end"));
    }
    Ok(())
}

fn read_extra(r: &mut Cursor, c: Chunk, doc: &mut Document) -> Result<()> {
    r.seek(c.begin)?;
    let arrays = r.nonnegative("EBXX array")?;
    let boxed = r.nonnegative("EBXX boxed value")?;
    r.ensure(c.end, arrays.saturating_add(boxed), 16, "EBXX")?;
    let record = |r: &mut Cursor, what: &'static str| -> Result<(u32, u32, u32, u16, u16)> {
        let offset = r.u32(Endian::Little)?;
        let at = r.position();
        let count = u32::try_from(r.i32(Endian::Little)?).map_err(|_| bad(what, at, "negative count"))?;
        let v = (
            offset,
            count,
            r.u32(Endian::Little)?,
            r.u16(Endian::Little)?,
            r.u16(Endian::Little)?,
        );
        validate_data_offset(doc, offset, 0, what)?;
        Ok(v)
    };
    let mut array_records = Vec::with_capacity(arrays);
    for _ in 0..arrays {
        let (offset, count, hash, encoded_type, class_ref) = record(r, "EBXX array")?;
        array_records.push(ArrayRecord {
            offset,
            count,
            hash,
            encoded_type,
            class_ref,
        });
    }
    let mut boxed_records = Vec::with_capacity(boxed);
    for _ in 0..boxed {
        let (offset, count, hash, encoded_type, class_ref) = record(r, "EBXX boxed value")?;
        boxed_records.push(BoxedValueRecord {
            offset,
            count,
            hash,
            encoded_type,
            class_ref,
            raw: Vec::new(),
        });
    }
    if r.position() != c.end {
        return Err(bad("EBXX", r.position(), "unexpected bytes at its end"));
    }
    doc.arrays = array_records;
    doc.boxed_values = boxed_records;
    Ok(())
}

fn string_at(d: &[u8], offset: usize, end: usize) -> Result<String> {
    let s = d.get(offset..end).filter(|s| !s.is_empty()).ok_or_else(|| {
        bad(
            "reflection string",
            offset,
            "offset is invalid: expected a string inside the chunk",
        )
    })?;
    let mut parts = s.splitn(2, |&b| b == 0);
    let (Some(text), Some(_)) = (parts.next(), parts.next()) else {
        return Err(bad(
            "reflection string",
            offset,
            "unterminated, expected a zero byte",
        ));
    };
    String::from_utf8(text.to_vec()).map_err(|_| bad("reflection string", offset, "is not UTF-8"))
}

/// The reflection table; returns each type's (guid, signature) for mapping instances.
fn read_reflection(
    r: &mut Cursor,
    c: Chunk,
    hashed: bool,
    doc: &mut Document,
) -> Result<Vec<([u8; 16], u32)>> {
    r.seek(c.begin)?;
    let nsig = r.nonnegative("reflection signature")?;
    r.ensure(c.end, nsig, 20, "reflection signature")?;
    let mut ids = Vec::with_capacity(nsig);
    for _ in 0..nsig {
        ids.push((r.array::<16>()?, r.u32(Endian::Little)?));
    }
    let ntypes = r.nonnegative("reflection type")?;
    r.ensure(c.end, ntypes, 16, "reflection type")?;
    for i in 0..ntypes {
        let at = r.position();
        let name_hash = r.u32(Endian::Little)?;
        let field_index = r.i32(Endian::Little)?;
        let field_count = r.u16(Endian::Little)?;
        let encoded_type = r.u16(Endian::Little)? >> 1;
        let size = r.u16(Endian::Little)?;
        let alignment = r.u16(Endian::Little)?;
        if alignment > 255 {
            return Err(bad("reflection type", at, "alignment is unsupported"));
        }
        let (guid, signature) = ids.get(i).copied().unwrap_or(([0; 16], 0));
        doc.types.push(TypeDescriptor {
            name: String::new(),
            name_hash,
            field_index,
            field_count,
            encoded_type,
            size,
            alignment,
            guid,
            signature,
        });
    }
    let nfields = r.nonnegative("reflection field")?;
    r.ensure(c.end, nfields, 12, "reflection field")?;
    for _ in 0..nfields {
        let name_hash = r.u32(Endian::Little)?;
        let data_offset = r.u32(Endian::Little)?;
        let encoded_type = r.u16(Endian::Little)? >> 1;
        let class_ref = r.u16(Endian::Little)?;
        doc.fields.push(FieldDescriptor {
            name: String::new(),
            name_hash,
            encoded_type,
            class_ref,
            data_offset,
        });
    }
    for t in &doc.types {
        let ok = usize::try_from(t.field_index).is_ok_and(|fi| {
            doc.fields
                .len()
                .checked_sub(fi)
                .is_some_and(|room| usize::from(t.field_count) <= room)
        });
        if !ok {
            return Err(bad(
                "reflection type",
                c.begin,
                format!("{:#x}: field range is invalid", t.name_hash),
            ));
        }
    }
    let ngroups = r.nonnegative("reflection group")?;
    r.ensure(c.end, ngroups, 12, "reflection group")?;
    for _ in 0..ngroups {
        doc.reflection_groups.push(ReflectionGroup {
            hash: r.u32(Endian::Little)?,
            count: r.u32(Endian::Little)?,
            first: r.u32(Endian::Little)?,
        });
    }
    let nmap = r.nonnegative("reflection mapping")?;
    r.ensure(c.end, nmap, 8, "reflection mapping")?;
    r.take(crate::at(0, nmap, 8))?;
    if hashed {
        let nnames = r.nonnegative("reflection name")?;
        r.ensure(c.end, nnames, 8, "reflection name")?;
        // a later record of the same hash replaces an earlier one, as in ReSkate's map
        let mut names = BTreeMap::new();
        for _ in 0..nnames {
            let h = r.u32(Endian::Little)?;
            names.insert(h, r.u32(Endian::Little)? as usize);
        }
        let strings = r.position();
        let lookup = |h: u32| -> Result<String> {
            let o = names.get(&h).ok_or_else(|| {
                bad(
                    "RFL2 name",
                    c.begin,
                    format!("{h:#x} is missing from {} names", names.len()),
                )
            })?;
            string_at(r.bytes(), strings.saturating_add(*o), c.end)
        };
        for t in &mut doc.types {
            t.name = lookup(t.name_hash)?;
        }
        for f in &mut doc.fields {
            f.name = lookup(f.name_hash)?;
        }
    } else {
        let strings = r.position();
        for t in &mut doc.types {
            t.name = string_at(r.bytes(), strings.saturating_add(t.name_hash as usize), c.end)?;
        }
        for f in &mut doc.fields {
            f.name = string_at(r.bytes(), strings.saturating_add(f.name_hash as usize), c.end)?;
        }
    }
    Ok(ids)
}

/// Reads the values of the document's instances (ReSkate's `ValueReader`).
struct Values<'a> {
    d: &'a [u8],
    r: Cursor<'a>,
    doc: &'a Document,
    /// array record offset -> its hash (the first record of an offset)
    array_hashes: BTreeMap<i64, u32>,
    /// instance data offset -> index (the first instance of an offset)
    instance_at: BTreeMap<i64, usize>,
    depth: u32,
    boxed_slots: Vec<u32>,
}

impl<'a> Values<'a> {
    fn object(&mut self, descriptor: usize, start: usize) -> Result<Object> {
        self.nest(start)?;
        let t = self
            .doc
            .types
            .get(descriptor)
            .ok_or_else(|| bad("EBX object", start, "type reference is invalid"))?;
        if start < self.doc.data_start || usize::from(t.size) > self.doc.data_end.saturating_sub(start) {
            return Err(bad("EBX object", start, "exceeds EBXD"));
        }
        let mut o = Object {
            descriptor,
            fields: Vec::new(),
        };
        self.fields(&mut o, descriptor, start)?;
        self.depth = self.depth.saturating_sub(1);
        Ok(o)
    }

    fn nest(&mut self, at: usize) -> Result<()> {
        if self.depth >= MAX_DEPTH {
            return Err(bad("EBX type", at, "types nest too deeply"));
        }
        self.depth = self.depth.saturating_add(1);
        Ok(())
    }

    fn fields(&mut self, out: &mut Object, type_index: usize, start: usize) -> Result<()> {
        let t = self
            .doc
            .types
            .get(type_index)
            .ok_or_else(|| bad("EBX type", start, "type reference is invalid"))?;
        let first = usize::try_from(t.field_index).unwrap_or(0);
        for k in 0..usize::from(t.field_count) {
            let di = first.saturating_add(k);
            let f = self.doc.fields.get(di).ok_or_else(|| {
                bad(
                    "EBX field",
                    start,
                    format!("field {di} of {} is invalid", self.doc.fields.len()),
                )
            })?;
            if f.ty() == FieldType::Inherited {
                let base = usize::from(f.class_ref);
                if base >= self.doc.types.len() {
                    return Err(bad("EBX base type", start, "is invalid"));
                }
                self.nest(start)?;
                self.fields(out, base, start)?;
                self.depth = self.depth.saturating_sub(1);
                continue;
            }
            let position = start.saturating_add(f.data_offset as usize);
            if position > self.doc.data_end {
                return Err(bad("EBX field", position, "offset exceeds EBXD"));
            }
            let mut value = self.field(f, position)?;
            if f.is_array()
                && let Value::Array(items, hash) = &mut value
                && !items.is_empty()
            {
                let disp = self
                    .d
                    .get(position..)
                    .and_then(|b| b.first_chunk::<4>())
                    .map(|b| i32::from_le_bytes(*b))
                    .ok_or_else(|| {
                        bad(
                            "EBX array",
                            position,
                            "array displacement past the end: expected 4 bytes",
                        )
                    })?;
                let target = data_relative(position, i64::from(disp), self.doc.data_start);
                *hash = self.array_hashes.get(&target).copied();
            }
            out.fields.push(FieldValue {
                descriptor: di,
                name: f.name.clone(),
                value,
            });
        }
        Ok(())
    }

    fn field(&mut self, f: &FieldDescriptor, position: usize) -> Result<Value> {
        if f.is_array() {
            self.r.seek(position)?;
            let disp = self.r.i32(Endian::Little)?;
            let target = data_relative(position, i64::from(disp), 0);
            let low = i64::try_from(self.doc.data_start.saturating_add(4)).unwrap_or(i64::MAX);
            let high = i64::try_from(self.doc.data_end).unwrap_or(i64::MAX);
            let target = match usize::try_from(target) {
                Ok(t) if (low..=high).contains(&target) => t,
                _ => return Err(bad("EBX array", position, "displacement exceeds EBXD")),
            };
            let count_at = target.saturating_sub(4);
            self.r.seek(count_at)?;
            let count = usize::try_from(self.r.i32(Endian::Little)?)
                .map_err(|_| bad("EBX array", count_at, "negative count"))?;
            if count > self.doc.data_end.saturating_sub(target) {
                return Err(bad("EBX array", target, format!("{count} elements exceed EBXD")));
            }
            self.r.seek(target)?;
            let mut items = Vec::with_capacity(count);
            for _ in 0..count {
                let element = self.r.position();
                items.push(self.value(f.ty(), f.class_ref, element)?);
                match f.ty() {
                    FieldType::Structure => {
                        let t = self
                            .doc
                            .types
                            .get(usize::from(f.class_ref))
                            .ok_or_else(|| bad("EBX array", element, "struct type is invalid"))?;
                        self.r.seek(element.saturating_add(usize::from(t.size)))?;
                    }
                    FieldType::Pointer | FieldType::CString => {
                        let p = align_up(self.r.position(), 8);
                        self.r.seek(p)?;
                    }
                    _ => {}
                }
            }
            return Ok(Value::Array(items, None));
        }
        self.r.seek(position)?;
        self.value(f.ty(), f.class_ref, position)
    }

    fn value(&mut self, ty: FieldType, class_ref: u16, position: usize) -> Result<Value> {
        let r = &mut self.r;
        Ok(match ty {
            FieldType::Boolean => Value::Bool(r.u8()? != 0),
            FieldType::Int8 => Value::Int(i64::from(r.u8()?.cast_signed())),
            FieldType::UInt8 => Value::UInt(u64::from(r.u8()?)),
            FieldType::Int16 => Value::Int(i64::from(r.u16(Endian::Little)?.cast_signed())),
            FieldType::UInt16 => Value::UInt(u64::from(r.u16(Endian::Little)?)),
            FieldType::Int32 | FieldType::Enumeration => Value::Int(i64::from(r.i32(Endian::Little)?)),
            FieldType::UInt32 => Value::UInt(u64::from(r.u32(Endian::Little)?)),
            FieldType::Int64 => Value::Int(r.i64(Endian::Little)?),
            FieldType::UInt64 => Value::UInt(r.u64(Endian::Little)?),
            FieldType::Float32 => Value::Float(widen_f32(u32::from_le_bytes(r.array()?))),
            FieldType::Float64 => Value::Float(f64::from_le_bytes(r.array()?)),
            FieldType::Guid => Value::Guid(r.array()?),
            FieldType::Sha1 => Value::Sha1(r.array()?),
            FieldType::ResourceRef => Value::Resource(r.u64(Endian::Little)?),
            FieldType::String => {
                let raw = r.take(32)?;
                Value::Str(raw.split(|&b| b == 0).next().unwrap_or_default().to_vec())
            }
            FieldType::CString => {
                let disp = r.u32(Endian::Little)?;
                Value::Str(self.relative_string(position, disp)?)
            }
            FieldType::FileRef => {
                let disp = r.u32(Endian::Little)?;
                r.take(4)?;
                Value::Str(self.relative_string(position, disp)?)
            }
            FieldType::Pointer => {
                let encoded = r.i32(Endian::Little)?;
                if encoded == 0 {
                    Value::Pointer(Pointer::Null)
                } else if encoded & 1 != 0 {
                    let index = usize::try_from(encoded >> 1)
                        .ok()
                        .filter(|&i| i < self.doc.imports.len())
                        .ok_or_else(|| bad("EBX pointer", position, "import is invalid"))?;
                    Value::Pointer(Pointer::External(index))
                } else {
                    let target = data_relative(position, i64::from(encoded), self.doc.data_start);
                    let i = *self
                        .instance_at
                        .get(&target)
                        .ok_or_else(|| bad("EBX pointer", position, "internal target is invalid"))?;
                    Value::Pointer(Pointer::Internal(i))
                }
            }
            FieldType::TypeRef | FieldType::Delegate => {
                let encoded = r.u32(Endian::Little)?;
                r.take(4)?;
                if encoded == 0 {
                    Value::TypeRef(TypeRef {
                        primitive: false,
                        primitive_type: None,
                        fixup_type: None,
                        encoded: 0,
                    })
                } else if encoded & 0x8000_0000 != 0 {
                    let bits = ((encoded & !0x8000_0000) >> 5) & 0x1F;
                    Value::TypeRef(TypeRef {
                        primitive: true,
                        primitive_type: Some(FieldType::from_bits(u16::try_from(bits).unwrap_or_default())),
                        fixup_type: None,
                        encoded,
                    })
                } else {
                    Value::TypeRef(TypeRef {
                        primitive: false,
                        primitive_type: None,
                        fixup_type: Some((encoded >> 2) as usize),
                        encoded,
                    })
                }
            }
            FieldType::BoxedValueRef => {
                let encoded_type = r.u32(Endian::Little)?;
                r.take(4)?;
                let disp = r.i64(Endian::Little)?;
                let target = data_relative(position.saturating_add(8), disp, self.doc.data_start);
                let slot = u32::try_from(position.saturating_sub(self.doc.data_start))
                    .map_err(|_| bad("EBX boxed value", position, "offset does not fit 32 bits"))?;
                self.boxed_slots.push(slot);
                Value::Boxed(BoxedRef {
                    encoded_type,
                    data_offset: target,
                    relative_offset: disp,
                })
            }
            FieldType::Structure => Value::Object(Box::new(self.object(usize::from(class_ref), position)?)),
            _ => Value::Nothing,
        })
    }

    fn relative_string(&mut self, base: usize, disp: u32) -> Result<Vec<u8>> {
        if disp == u32::MAX {
            return Ok(Vec::new());
        }
        let target = base.saturating_add(disp as usize);
        if !(self.doc.data_start..self.doc.data_end).contains(&target) {
            return Err(bad("EBX string", base, "displacement exceeds EBXD"));
        }
        let saved = self.r.position();
        self.r.seek(target)?;
        let s = self.r.c_string()?;
        if self.r.position() > self.doc.data_end {
            return Err(bad("EBX string", target, "exceeds EBXD"));
        }
        self.r.seek(saved)?;
        Ok(s)
    }
}

/// Reads an EBX document into typed values.
pub fn read(bytes: &[u8]) -> Result<Document> {
    let mut r = Cursor::new(bytes);
    let chunks = read_chunks(&mut r)?;
    let data = one_chunk(&chunks, EBXD, "EBXD", true)?.ok_or_else(|| bad("EBXD", 0, "missing"))?;
    let fixup = one_chunk(&chunks, EFIX, "EFIX", true)?.ok_or_else(|| bad("EFIX", 0, "missing"))?;
    let extra = one_chunk(&chunks, EBXX, "EBXX", true)?.ok_or_else(|| bad("EBXX", 0, "missing"))?;
    let refl = one_chunk(&chunks, REFL, "REFL", false)?;
    let rfl2 = one_chunk(&chunks, RFL2, "RFL2", false)?;
    let (reflection, hashed) = match (refl, rfl2) {
        (Some(c), None) => (c, false),
        (None, Some(c)) => (c, true),
        _ => return Err(bad("RIFF", 0, "must hold exactly one REFL or RFL2 chunk")),
    };
    let data_start = align_up(data.begin, 16);
    if data_start > data.end {
        return Err(bad("EBXD", data.begin, "alignment exceeds the chunk"));
    }
    r.seek(8)?;
    let serialized_layout = r.u32(Endian::Big)? == EBXS;
    let mut doc = Document {
        file_guid: [0; 16],
        root_type: String::new(),
        data_start,
        data_end: data.end,
        arrays_offset: 0,
        boxed_values_offset: 0,
        strings_offset: 0,
        serialized_layout,
        hashed_reflection_names: hashed,
        reflection_data: bytes
            .get(reflection.begin..reflection.end)
            .ok_or_else(|| bad("RIFF", reflection.begin, "reflection chunk past the end"))?
            .to_vec(),
        fixup_type_guids: Vec::new(),
        fixup_type_signatures: Vec::new(),
        boxed_reference_offsets: Vec::new(),
        types: Vec::new(),
        fields: Vec::new(),
        instances: Vec::new(),
        imports: Vec::new(),
        arrays: Vec::new(),
        boxed_values: Vec::new(),
        pointer_offsets: Vec::new(),
        resource_ref_offsets: Vec::new(),
        import_offsets: Vec::new(),
        type_info_offsets: Vec::new(),
        boxed_value_slots: Vec::new(),
        payload: bytes
            .get(data_start..data.end)
            .ok_or_else(|| bad("EBXD", data_start, "data chunk past the end"))?
            .to_vec(),
        reflection_groups: Vec::new(),
    };
    read_fixup(&mut r, fixup, &mut doc)?;
    read_extra(&mut r, extra, &mut doc)?;
    let ids = read_reflection(&mut r, reflection, hashed, &mut doc)?;
    // map instances to reflection types by (guid, signature)
    for inst in &mut doc.instances {
        let slot = usize::from(inst.fixup_type);
        let (Some(guid), Some(signature)) = (
            doc.fixup_type_guids.get(slot),
            doc.fixup_type_signatures.get(slot),
        ) else {
            continue;
        };
        inst.descriptor = ids.iter().position(|&(g, s)| g == *guid && s == *signature);
    }
    if let Some(d) = doc.instances.first().and_then(|i| i.descriptor)
        && let Some(t) = doc.types.get(d)
    {
        doc.root_type = t.name.clone();
    }
    // values
    let mut instances = std::mem::take(&mut doc.instances);
    {
        let mut array_hashes = BTreeMap::new();
        for a in &doc.arrays {
            array_hashes.entry(i64::from(a.offset)).or_insert(a.hash);
        }
        let mut instance_at = BTreeMap::new();
        for (i, inst) in instances.iter().enumerate() {
            instance_at.entry(i64::from(inst.data_offset)).or_insert(i);
        }
        let mut v = Values {
            d: bytes,
            r: Cursor::new(bytes),
            doc: &doc,
            array_hashes,
            instance_at,
            depth: 0,
            boxed_slots: Vec::new(),
        };
        for inst in &mut instances {
            let Some(d) = inst.descriptor else { continue };
            let Some(t) = doc.types.get(d) else { continue };
            let start = doc.data_start.saturating_add(inst.data_offset as usize);
            if inst.exported {
                let guid = start
                    .checked_sub(16)
                    .filter(|&at| at >= doc.data_start)
                    .and_then(|at| bytes.get(at..)?.first_chunk::<16>())
                    .ok_or_else(|| bad("EBX instance", start, "exported instance has no GUID"))?;
                inst.guid = *guid;
            }
            let size = usize::from(t.size);
            if size > doc.data_end.saturating_sub(start) {
                return Err(bad("EBX instance", start, "exceeds EBXD"));
            }
            inst.raw_image = bytes
                .get(start..start.saturating_add(size))
                .ok_or_else(|| bad("EBX instance", start, "exceeds the document"))?
                .to_vec();
            inst.object = Some(v.object(d, start)?);
        }
        let slots = std::mem::take(&mut v.boxed_slots);
        doc.boxed_value_slots = slots;
    }
    doc.instances = instances;
    // boxed value bytes: up to the next record, the last up to the strings
    doc.boxed_values.sort_by_key(|b| b.offset);
    let mut boxed = std::mem::take(&mut doc.boxed_values);
    let ends: Vec<u32> = (boxed.iter().skip(1).map(|b| b.offset))
        .chain(std::iter::once(doc.strings_offset))
        .collect();
    for (b, &end) in boxed.iter_mut().zip(&ends) {
        let start = b.offset;
        let Some(len) = end.checked_sub(start) else {
            return Err(bad("EBXX boxed value", start as usize, "records are not ordered"));
        };
        validate_data_offset(&doc, start, len as usize, "EBXX boxed value bytes")?;
        b.raw = doc
            .payload
            .get(start as usize..end as usize)
            .ok_or_else(|| bad("EBXX boxed value", start as usize, "bytes exceed EBXD"))?
            .to_vec();
    }
    doc.boxed_values = boxed;
    Ok(doc)
}

/// The document's own GUID (what another document's import names it by), without reading the rest.
pub fn read_file_guid(bytes: &[u8]) -> Result<[u8; 16]> {
    let mut r = Cursor::new(bytes);
    let chunks = read_chunks(&mut r)?;
    let c = one_chunk(&chunks, EFIX, "EFIX", true)?.ok_or_else(|| bad("EFIX", 0, "missing"))?;
    r.seek(c.begin)?;
    Ok(r.array()?)
}