object 0.39.1

A unified interface for reading and writing object file formats.
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
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt::{self, Debug};
use core::{mem, slice};

use crate::endian::{Endian, Endianness, U16, U32, U64};
use crate::read::{Architecture, Error, File, ReadError, ReadRef, Result};
use crate::{macho, SkipDebugList};

/// A parsed representation of the dyld shared cache.
#[derive(Debug)]
pub struct DyldCache<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    endian: E,
    data: R,
    /// The first entry is the main cache file, and the rest are subcaches.
    files: Vec<DyldFile<'data, E, R>>,
    images: &'data [macho::DyldCacheImageInfo<E>],
    arch: Architecture,
}

/// A slice of structs describing each subcache.
///
/// The struct gained an additional field (the file suffix) in dyld-1042.1 (macOS 13 / iOS 16),
/// so this is an enum of the two possible slice types.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum DyldSubCacheSlice<'data, E: Endian> {
    /// V1, used between dyld-940 and dyld-1042.1.
    V1(&'data [macho::DyldSubCacheEntryV1<E>]),
    /// V2, used since dyld-1042.1.
    V2(&'data [macho::DyldSubCacheEntryV2<E>]),
}

// This is the offset of the end of the images_count field.
const MIN_HEADER_SIZE_SUBCACHES_V1: u32 = 0x1c8;

// This is the offset of the end of the cache_sub_type field.
const MIN_HEADER_SIZE_SUBCACHES_V2: u32 = 0x1d0;

impl<'data, E, R> DyldCache<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    /// Return the suffixes of the subcache files given the data of the main cache file.
    ///
    /// Each of these should be appended to the path of the main cache file.
    pub fn subcache_suffixes(data: R) -> Result<Vec<String>> {
        let header = macho::DyldCacheHeader::<E>::parse(data)?;
        let (_arch, endian) = header.parse_magic()?;
        let Some(subcaches_info) = header.subcaches(endian, data)? else {
            return Ok(Vec::new());
        };
        let mut subcache_suffixes: Vec<String> = match subcaches_info {
            DyldSubCacheSlice::V1(subcaches) => {
                // macOS 12: Subcaches have the file suffixes .1, .2, .3 etc.
                (1..subcaches.len() + 1).map(|i| format!(".{i}")).collect()
            }
            DyldSubCacheSlice::V2(subcaches) => {
                // macOS 13+: The subcache file suffix is written down in the header of the main cache.
                subcaches
                    .iter()
                    .map(|s| {
                        // The suffix is a nul-terminated string in a fixed-size byte array.
                        let suffix = s.file_suffix;
                        let len = suffix.iter().position(|&c| c == 0).unwrap_or(suffix.len());
                        String::from_utf8_lossy(&suffix[..len]).to_string()
                    })
                    .collect()
            }
        };
        if header.symbols_subcache_uuid(endian).is_some() {
            subcache_suffixes.push(".symbols".to_string());
        }
        Ok(subcache_suffixes)
    }

    /// Parse the raw dyld shared cache data.
    ///
    /// For shared caches from macOS 12 / iOS 15 and above, the subcache files need to be
    /// supplied as well, in the correct order. Use [`Self::subcache_suffixes`] to obtain
    /// the suffixes for the path of the files.
    pub fn parse(data: R, subcache_data: &[R]) -> Result<Self> {
        let header = macho::DyldCacheHeader::parse(data)?;
        let (arch, endian) = header.parse_magic()?;

        let mut files = Vec::new();
        let mappings = header.mappings(endian, data)?;
        files.push(DyldFile {
            data: SkipDebugList(data),
            mappings,
        });

        let symbols_subcache_uuid = header.symbols_subcache_uuid(endian);
        let subcaches_info = header.subcaches(endian, data)?;
        let subcaches_count = match subcaches_info {
            Some(DyldSubCacheSlice::V1(subcaches)) => subcaches.len(),
            Some(DyldSubCacheSlice::V2(subcaches)) => subcaches.len(),
            None => 0,
        };
        if subcache_data.len() != subcaches_count + symbols_subcache_uuid.is_some() as usize {
            return Err(Error("Incorrect number of SubCaches"));
        }

        // Split out the .symbols subcache data from the other subcaches.
        let (symbols_subcache_data_and_uuid, subcache_data) =
            if let Some(symbols_uuid) = symbols_subcache_uuid {
                let (sym_data, rest_data) = subcache_data.split_last().unwrap();
                (Some((*sym_data, symbols_uuid)), rest_data)
            } else {
                (None, subcache_data)
            };

        // Read the regular SubCaches, if present.
        if let Some(subcaches_info) = subcaches_info {
            let (v1, v2) = match subcaches_info {
                DyldSubCacheSlice::V1(s) => (s, &[][..]),
                DyldSubCacheSlice::V2(s) => (&[][..], s),
            };
            let uuids = v1.iter().map(|e| &e.uuid).chain(v2.iter().map(|e| &e.uuid));
            for (&data, uuid) in subcache_data.iter().zip(uuids) {
                let header = macho::DyldCacheHeader::<E>::parse(data)?;
                if &header.uuid != uuid {
                    return Err(Error("Unexpected SubCache UUID"));
                }
                let mappings = header.mappings(endian, data)?;
                files.push(DyldFile {
                    data: SkipDebugList(data),
                    mappings,
                });
            }
        }

        // Read the .symbols SubCache, if present.
        // Other than the UUID verification, the symbols SubCache is currently unused.
        let _symbols_subcache = match symbols_subcache_data_and_uuid {
            Some((data, uuid)) => {
                let header = macho::DyldCacheHeader::<E>::parse(data)?;
                if header.uuid != uuid {
                    return Err(Error("Unexpected .symbols SubCache UUID"));
                }
                let mappings = header.mappings(endian, data)?;
                Some(DyldFile {
                    data: SkipDebugList(data),
                    mappings,
                })
            }
            None => None,
        };

        let images = header.images(endian, data)?;
        Ok(DyldCache {
            endian,
            data,
            files,
            images,
            arch,
        })
    }

    /// Get the architecture type of the file.
    pub fn architecture(&self) -> Architecture {
        self.arch
    }

    /// Get the endianness of the file.
    #[inline]
    pub fn endianness(&self) -> Endianness {
        if self.is_little_endian() {
            Endianness::Little
        } else {
            Endianness::Big
        }
    }

    /// Get the data of the main cache file.
    #[inline]
    pub fn data(&self) -> R {
        self.data
    }

    /// Return true if the file is little endian, false if it is big endian.
    pub fn is_little_endian(&self) -> bool {
        self.endian.is_little_endian()
    }

    /// Iterate over the images in this cache.
    pub fn images<'cache>(&'cache self) -> DyldCacheImageIterator<'data, 'cache, E, R> {
        DyldCacheImageIterator {
            cache: self,
            iter: self.images.iter(),
        }
    }

    /// Return all the mappings in this cache.
    pub fn mappings<'cache>(
        &'cache self,
    ) -> impl Iterator<Item = DyldCacheMapping<'data, E, R>> + 'cache {
        let endian = self.endian;
        self.files
            .iter()
            .flat_map(move |file| file.mappings(endian))
    }

    /// Find the address in a mapping and return the cache or subcache data it was found in,
    /// together with the translated file offset.
    pub fn data_and_offset_for_address(&self, address: u64) -> Option<(R, u64)> {
        for file in &self.files {
            if let Some(file_offset) = file.address_to_file_offset(self.endian, address) {
                return Some((file.data.0, file_offset));
            }
        }
        None
    }
}

/// The data for one file in the cache.
#[derive(Debug)]
struct DyldFile<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    data: SkipDebugList<R>,
    mappings: DyldCacheMappingSlice<'data, E>,
}

impl<'data, E, R> DyldFile<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    /// Return an iterator for the mappings.
    fn mappings(&self, endian: E) -> DyldCacheMappingIterator<'data, E, R> {
        let iter = match self.mappings {
            DyldCacheMappingSlice::V1(info) => DyldCacheMappingVersionIterator::V1(info.iter()),
            DyldCacheMappingSlice::V2(info) => DyldCacheMappingVersionIterator::V2(info.iter()),
        };
        DyldCacheMappingIterator {
            endian,
            data: self.data.0,
            iter,
        }
    }

    /// Find the file offset an address in the mappings.
    fn address_to_file_offset(&self, endian: E, address: u64) -> Option<u64> {
        for mapping in self.mappings(endian) {
            let mapping_address = mapping.address();
            if address >= mapping_address && address < mapping_address.wrapping_add(mapping.size())
            {
                return Some(address - mapping_address + mapping.file_offset());
            }
        }
        None
    }
}

/// An iterator over all the images (dylibs) in the dyld shared cache.
#[derive(Debug)]
pub struct DyldCacheImageIterator<'data, 'cache, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    cache: &'cache DyldCache<'data, E, R>,
    iter: slice::Iter<'data, macho::DyldCacheImageInfo<E>>,
}

impl<'data, 'cache, E, R> Iterator for DyldCacheImageIterator<'data, 'cache, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    type Item = DyldCacheImage<'data, 'cache, E, R>;

    fn next(&mut self) -> Option<DyldCacheImage<'data, 'cache, E, R>> {
        let image_info = self.iter.next()?;
        Some(DyldCacheImage {
            cache: self.cache,
            image_info,
        })
    }
}

/// One image (dylib) from inside the dyld shared cache.
#[derive(Debug)]
pub struct DyldCacheImage<'data, 'cache, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    pub(crate) cache: &'cache DyldCache<'data, E, R>,
    image_info: &'data macho::DyldCacheImageInfo<E>,
}

impl<'data, 'cache, E, R> DyldCacheImage<'data, 'cache, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    /// Return the raw data structure for this image.
    pub fn info(&self) -> &'data macho::DyldCacheImageInfo<E> {
        self.image_info
    }

    /// The file system path of this image.
    pub fn path(&self) -> Result<&'data str> {
        let path = self.image_info.path(self.cache.endian, self.cache.data)?;
        // The path should always be ascii, so from_utf8 should always succeed.
        let path = core::str::from_utf8(path).map_err(|_| Error("Path string not valid utf-8"))?;
        Ok(path)
    }

    /// The subcache data which contains the Mach-O header for this image,
    /// together with the file offset at which this image starts.
    pub fn image_data_and_offset(&self) -> Result<(R, u64)> {
        let address = self.image_info.address.get(self.cache.endian);
        self.cache
            .data_and_offset_for_address(address)
            .ok_or(Error("Address not found in any mapping"))
    }

    /// Parse this image into an Object.
    pub fn parse_object(&self) -> Result<File<'data, R>> {
        File::parse_dyld_cache_image(self)
    }
}

/// The array of mappings for a single dyld cache file.
///
/// The mappings gained slide info in dyld-832.7 (macOS 11)
/// so this is an enum of the two possible slice types.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum DyldCacheMappingSlice<'data, E: Endian = Endianness> {
    /// V1, used before dyld-832.7.
    V1(&'data [macho::DyldCacheMappingInfo<E>]),
    /// V2, used since dyld-832.7.
    V2(&'data [macho::DyldCacheMappingAndSlideInfo<E>]),
}

// This is the offset of the end of the mapping_with_slide_count field.
const MIN_HEADER_SIZE_MAPPINGS_V2: u32 = 0x140;

/// An iterator over all the mappings for one subcache in a dyld shared cache.
#[derive(Debug)]
pub struct DyldCacheMappingIterator<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    endian: E,
    data: R,
    iter: DyldCacheMappingVersionIterator<'data, E>,
}

#[derive(Debug)]
enum DyldCacheMappingVersionIterator<'data, E = Endianness>
where
    E: Endian,
{
    V1(slice::Iter<'data, macho::DyldCacheMappingInfo<E>>),
    V2(slice::Iter<'data, macho::DyldCacheMappingAndSlideInfo<E>>),
}

impl<'data, E, R> Iterator for DyldCacheMappingIterator<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    type Item = DyldCacheMapping<'data, E, R>;

    fn next(&mut self) -> Option<Self::Item> {
        let info = match &mut self.iter {
            DyldCacheMappingVersionIterator::V1(iter) => DyldCacheMappingVersion::V1(iter.next()?),
            DyldCacheMappingVersionIterator::V2(iter) => DyldCacheMappingVersion::V2(iter.next()?),
        };
        Some(DyldCacheMapping {
            endian: self.endian,
            data: self.data,
            info,
        })
    }
}

/// Information about a mapping.
#[derive(Clone, Copy)]
pub struct DyldCacheMapping<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    endian: E,
    data: R,
    info: DyldCacheMappingVersion<'data, E>,
}

#[derive(Clone, Copy)]
enum DyldCacheMappingVersion<'data, E = Endianness>
where
    E: Endian,
{
    V1(&'data macho::DyldCacheMappingInfo<E>),
    V2(&'data macho::DyldCacheMappingAndSlideInfo<E>),
}

impl<'data, E, R> Debug for DyldCacheMapping<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DyldCacheMapping")
            .field("address", &format_args!("{:#x}", self.address()))
            .field("size", &format_args!("{:#x}", self.size()))
            .field("file_offset", &format_args!("{:#x}", self.file_offset()))
            .field("max_prot", &format_args!("{:#x}", self.max_prot()))
            .field("init_prot", &format_args!("{:#x}", self.init_prot()))
            .finish()
    }
}

impl<'data, E, R> DyldCacheMapping<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    /// The mapping address
    pub fn address(&self) -> u64 {
        match self.info {
            DyldCacheMappingVersion::V1(info) => info.address.get(self.endian),
            DyldCacheMappingVersion::V2(info) => info.address.get(self.endian),
        }
    }

    /// The mapping size
    pub fn size(&self) -> u64 {
        match self.info {
            DyldCacheMappingVersion::V1(info) => info.size.get(self.endian),
            DyldCacheMappingVersion::V2(info) => info.size.get(self.endian),
        }
    }

    /// The mapping file offset
    pub fn file_offset(&self) -> u64 {
        match self.info {
            DyldCacheMappingVersion::V1(info) => info.file_offset.get(self.endian),
            DyldCacheMappingVersion::V2(info) => info.file_offset.get(self.endian),
        }
    }

    /// The mapping maximum protection
    pub fn max_prot(&self) -> u32 {
        match self.info {
            DyldCacheMappingVersion::V1(info) => info.max_prot.get(self.endian),
            DyldCacheMappingVersion::V2(info) => info.max_prot.get(self.endian),
        }
    }

    /// The mapping initial protection
    pub fn init_prot(&self) -> u32 {
        match self.info {
            DyldCacheMappingVersion::V1(info) => info.init_prot.get(self.endian),
            DyldCacheMappingVersion::V2(info) => info.init_prot.get(self.endian),
        }
    }

    /// The mapping data
    pub fn data(&self) -> Result<&'data [u8]> {
        self.data
            .read_bytes_at(self.file_offset(), self.size())
            .read_error("Failed to read bytes for mapping")
    }

    /// Relocations for the mapping
    pub fn relocations(&self) -> Result<DyldCacheRelocationIterator<'data, E, R>> {
        let data = self.data;
        let endian = self.endian;
        let version = match self.info {
            DyldCacheMappingVersion::V1(_) => DyldCacheRelocationIteratorVersion::None,
            DyldCacheMappingVersion::V2(mapping) => match mapping.slide(self.endian, self.data)? {
                DyldCacheSlideInfo::None => DyldCacheRelocationIteratorVersion::None,
                DyldCacheSlideInfo::V2 {
                    slide,
                    page_starts,
                    page_extras,
                } => {
                    let delta_mask = slide.delta_mask.get(endian);
                    let delta_shift = delta_mask.trailing_zeros();
                    DyldCacheRelocationIteratorVersion::V2(DyldCacheRelocationIteratorV2 {
                        data,
                        endian,
                        mapping_file_offset: mapping.file_offset.get(endian),
                        page_size: slide.page_size.get(endian).into(),
                        delta_mask,
                        delta_shift,
                        value_add: slide.value_add.get(endian),
                        page_starts,
                        page_extras,
                        state: RelocationStateV2::Start,
                        start_index: 0,
                        extra_index: 0,
                        page_offset: 0,
                        offset: 0,
                    })
                }
                DyldCacheSlideInfo::V3 { slide, page_starts } => {
                    DyldCacheRelocationIteratorVersion::V3(DyldCacheRelocationIteratorV3 {
                        data,
                        endian,
                        mapping_file_offset: mapping.file_offset.get(endian),
                        page_size: slide.page_size.get(endian).into(),
                        auth_value_add: slide.auth_value_add.get(endian),
                        page_starts,
                        state: RelocationStateV3::Start,
                        start_index: 0,
                        offset: 0,
                    })
                }
                DyldCacheSlideInfo::V5 { slide, page_starts } => {
                    DyldCacheRelocationIteratorVersion::V5(DyldCacheRelocationIteratorV5 {
                        data,
                        endian,
                        mapping_file_offset: mapping.file_offset.get(endian),
                        page_size: slide.page_size.get(endian).into(),
                        value_add: slide.value_add.get(endian),
                        page_starts,
                        state: RelocationStateV5::Start,
                        start_index: 0,
                        offset: 0,
                    })
                }
            },
        };
        Ok(DyldCacheRelocationIterator { version })
    }
}

/// The slide info for a dyld cache mapping, including variable length arrays.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum DyldCacheSlideInfo<'data, E: Endian> {
    None,
    V2 {
        slide: &'data macho::DyldCacheSlideInfo2<E>,
        page_starts: &'data [U16<E>],
        page_extras: &'data [U16<E>],
    },
    V3 {
        slide: &'data macho::DyldCacheSlideInfo3<E>,
        page_starts: &'data [U16<E>],
    },
    V5 {
        slide: &'data macho::DyldCacheSlideInfo5<E>,
        page_starts: &'data [U16<E>],
    },
}

/// An iterator over relocations in a mapping
#[derive(Debug)]
pub struct DyldCacheRelocationIterator<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    version: DyldCacheRelocationIteratorVersion<'data, E, R>,
}

impl<'data, E, R> Iterator for DyldCacheRelocationIterator<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    type Item = Result<DyldRelocation>;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.version {
            DyldCacheRelocationIteratorVersion::None => Ok(None),
            DyldCacheRelocationIteratorVersion::V2(iter) => iter.next(),
            DyldCacheRelocationIteratorVersion::V3(iter) => iter.next(),
            DyldCacheRelocationIteratorVersion::V5(iter) => iter.next(),
        }
        .transpose()
    }
}

#[derive(Debug)]
enum DyldCacheRelocationIteratorVersion<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    None,
    V2(DyldCacheRelocationIteratorV2<'data, E, R>),
    V3(DyldCacheRelocationIteratorV3<'data, E, R>),
    V5(DyldCacheRelocationIteratorV5<'data, E, R>),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum RelocationStateV2 {
    Start,
    Extra,
    Page,
    PageExtra,
}

#[derive(Debug)]
struct DyldCacheRelocationIteratorV2<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    data: R,
    endian: E,
    mapping_file_offset: u64,
    page_size: u64,
    delta_mask: u64,
    delta_shift: u32,
    value_add: u64,
    page_starts: &'data [U16<E>],
    page_extras: &'data [U16<E>],

    state: RelocationStateV2,
    /// The next index within page_starts.
    start_index: usize,
    /// The next index within page_extras.
    extra_index: usize,
    /// The current page offset within the mapping.
    page_offset: u64,
    /// The offset of the next linked list entry within the page.
    offset: u64,
}

impl<'data, E, R> DyldCacheRelocationIteratorV2<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    fn next(&mut self) -> Result<Option<DyldRelocation>> {
        loop {
            match self.state {
                RelocationStateV2::Start => {
                    let Some(page_start) = self.page_starts.get(self.start_index) else {
                        return Ok(None);
                    };
                    self.page_offset = self.start_index as u64 * self.page_size;
                    self.start_index += 1;

                    let page_start = page_start.get(self.endian);
                    if page_start & macho::DYLD_CACHE_SLIDE_PAGE_ATTR_NO_REBASE != 0 {
                        self.state = RelocationStateV2::Start;
                    } else if page_start & macho::DYLD_CACHE_SLIDE_PAGE_ATTR_EXTRA != 0 {
                        self.state = RelocationStateV2::Extra;
                        self.extra_index =
                            usize::from(page_start & !macho::DYLD_CACHE_SLIDE_PAGE_ATTRS);
                    } else {
                        self.state = RelocationStateV2::Page;
                        self.offset =
                            u64::from(page_start & !macho::DYLD_CACHE_SLIDE_PAGE_ATTRS) * 4;
                    }
                }
                RelocationStateV2::Extra => {
                    let Some(page_extra) = self.page_extras.get(self.extra_index) else {
                        return Ok(None);
                    };
                    self.extra_index += 1;

                    let page_extra = page_extra.get(self.endian);
                    self.offset = u64::from(page_extra & !macho::DYLD_CACHE_SLIDE_PAGE_ATTRS) * 4;
                    if page_extra & macho::DYLD_CACHE_SLIDE_PAGE_ATTR_END != 0 {
                        self.state = RelocationStateV2::Page;
                    } else {
                        self.state = RelocationStateV2::PageExtra;
                    }
                }
                RelocationStateV2::Page | RelocationStateV2::PageExtra => {
                    let offset = self.offset;
                    let pointer = self
                        .data
                        .read_at::<U64<E>>(self.mapping_file_offset + self.page_offset + offset)
                        .read_error("Invalid dyld cache slide pointer offset")?
                        .get(self.endian);

                    let next = (pointer & self.delta_mask) >> self.delta_shift;
                    if next == 0 {
                        if self.state == RelocationStateV2::PageExtra {
                            self.state = RelocationStateV2::Extra
                        } else {
                            self.state = RelocationStateV2::Start
                        };
                    } else {
                        self.offset = offset + next * 4;
                    };

                    let value = pointer & !self.delta_mask;
                    if value != 0 {
                        return Ok(Some(DyldRelocation {
                            offset,
                            value: value + self.value_add,
                            auth: None,
                        }));
                    }
                }
            }
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum RelocationStateV3 {
    Start,
    Page,
}

#[derive(Debug)]
struct DyldCacheRelocationIteratorV3<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    data: R,
    endian: E,
    mapping_file_offset: u64,
    auth_value_add: u64,
    page_size: u64,
    page_starts: &'data [U16<E>],

    state: RelocationStateV3,
    /// Index of the page within the mapping.
    start_index: usize,
    /// The current offset within the mapping.
    offset: u64,
}

impl<'data, E, R> DyldCacheRelocationIteratorV3<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    fn next(&mut self) -> Result<Option<DyldRelocation>> {
        loop {
            match self.state {
                RelocationStateV3::Start => {
                    let Some(page_start) = self.page_starts.get(self.start_index) else {
                        return Ok(None);
                    };
                    let page_offset = self.start_index as u64 * self.page_size;
                    self.start_index += 1;

                    let page_start = page_start.get(self.endian);
                    if page_start == macho::DYLD_CACHE_SLIDE_V3_PAGE_ATTR_NO_REBASE {
                        self.state = RelocationStateV3::Start;
                    } else {
                        self.state = RelocationStateV3::Page;
                        self.offset = page_offset + u64::from(page_start);
                    }
                }
                RelocationStateV3::Page => {
                    let offset = self.offset;
                    let pointer = self
                        .data
                        .read_at::<U64<E>>(self.mapping_file_offset + offset)
                        .read_error("Invalid dyld cache slide pointer offset")?
                        .get(self.endian);
                    let pointer = macho::DyldCacheSlidePointer3(pointer);

                    let next = pointer.next();
                    if next == 0 {
                        self.state = RelocationStateV3::Start;
                    } else {
                        self.offset = offset + next * 8;
                    }

                    if pointer.is_auth() {
                        let value = pointer.runtime_offset() + self.auth_value_add;
                        let key = match pointer.key() {
                            1 => macho::PtrauthKey::IB,
                            2 => macho::PtrauthKey::DA,
                            3 => macho::PtrauthKey::DB,
                            _ => macho::PtrauthKey::IA,
                        };
                        let auth = Some(DyldRelocationAuth {
                            key,
                            diversity: pointer.diversity(),
                            addr_div: pointer.addr_div(),
                        });
                        return Ok(Some(DyldRelocation {
                            offset,
                            value,
                            auth,
                        }));
                    } else {
                        let value = pointer.target() | pointer.high8() << 56;
                        return Ok(Some(DyldRelocation {
                            offset,
                            value,
                            auth: None,
                        }));
                    };
                }
            }
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum RelocationStateV5 {
    Start,
    Page,
}

#[derive(Debug)]
struct DyldCacheRelocationIteratorV5<'data, E = Endianness, R = &'data [u8]>
where
    E: Endian,
    R: ReadRef<'data>,
{
    data: R,
    endian: E,
    mapping_file_offset: u64,
    page_size: u64,
    value_add: u64,
    page_starts: &'data [U16<E>],

    state: RelocationStateV5,
    /// The next index within page_starts.
    start_index: usize,
    /// The current offset within the mapping.
    offset: u64,
}

impl<'data, E, R> DyldCacheRelocationIteratorV5<'data, E, R>
where
    E: Endian,
    R: ReadRef<'data>,
{
    fn next(&mut self) -> Result<Option<DyldRelocation>> {
        loop {
            match self.state {
                RelocationStateV5::Start => {
                    let Some(page_start) = self.page_starts.get(self.start_index) else {
                        return Ok(None);
                    };
                    let page_offset = self.start_index as u64 * self.page_size;
                    self.start_index += 1;

                    let page_start = page_start.get(self.endian);
                    if page_start == macho::DYLD_CACHE_SLIDE_V5_PAGE_ATTR_NO_REBASE {
                        self.state = RelocationStateV5::Start;
                    } else {
                        self.state = RelocationStateV5::Page;
                        self.offset = page_offset + u64::from(page_start);
                    }
                }
                RelocationStateV5::Page => {
                    let offset = self.offset;
                    let pointer = self
                        .data
                        .read_at::<U64<E>>(self.mapping_file_offset + offset)
                        .read_error("Invalid dyld cache slide pointer offset")?
                        .get(self.endian);
                    let pointer = macho::DyldCacheSlidePointer5(pointer);

                    let next = pointer.next();
                    if next == 0 {
                        self.state = RelocationStateV5::Start;
                    } else {
                        self.offset = offset + next * 8;
                    }

                    let mut value = pointer.runtime_offset() + self.value_add;
                    let auth = if pointer.is_auth() {
                        let key = if pointer.key_is_data() {
                            macho::PtrauthKey::DA
                        } else {
                            macho::PtrauthKey::IA
                        };
                        Some(DyldRelocationAuth {
                            key,
                            diversity: pointer.diversity(),
                            addr_div: pointer.addr_div(),
                        })
                    } else {
                        value |= pointer.high8() << 56;
                        None
                    };
                    return Ok(Some(DyldRelocation {
                        offset,
                        value,
                        auth,
                    }));
                }
            }
        }
    }
}

/// A cache mapping relocation.
pub struct DyldRelocation {
    /// The offset of the relocation within the mapping.
    ///
    /// This can be added to either the mapping file offset or the
    /// mapping address.
    pub offset: u64,
    /// The value to be relocated.
    pub value: u64,
    /// The pointer authentication data, if present.
    pub auth: Option<DyldRelocationAuth>,
}

impl Debug for DyldRelocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DyldRelocation")
            .field("offset", &format_args!("{:#x}", self.offset))
            .field("value", &format_args!("{:#x}", self.value))
            .field("auth", &self.auth)
            .finish()
    }
}

/// Pointer authentication data.
///
/// This is used for signing pointers for the arm64e ABI.
pub struct DyldRelocationAuth {
    /// The key used to generate the signed value.
    pub key: macho::PtrauthKey,
    /// The integer diversity value.
    pub diversity: u16,
    /// Whether the address should be blended with the diversity value.
    pub addr_div: bool,
}

impl Debug for DyldRelocationAuth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ptrauth")
            .field("key", &self.key)
            .field("diversity", &format_args!("{:#x}", self.diversity))
            .field("addr_div", &self.addr_div)
            .finish()
    }
}

impl<E: Endian> macho::DyldCacheHeader<E> {
    /// Read the dyld cache header.
    pub fn parse<'data, R: ReadRef<'data>>(data: R) -> Result<&'data Self> {
        data.read_at::<macho::DyldCacheHeader<E>>(0)
            .read_error("Invalid dyld cache header size or alignment")
    }

    /// Returns (arch, endian) based on the magic string.
    pub fn parse_magic(&self) -> Result<(Architecture, E)> {
        let (arch, is_big_endian) = match &self.magic {
            b"dyld_v1    i386\0" => (Architecture::I386, false),
            b"dyld_v1  x86_64\0" => (Architecture::X86_64, false),
            b"dyld_v1 x86_64h\0" => (Architecture::X86_64, false),
            b"dyld_v1     ppc\0" => (Architecture::PowerPc, true),
            b"dyld_v1   armv6\0" => (Architecture::Arm, false),
            b"dyld_v1   armv7\0" => (Architecture::Arm, false),
            b"dyld_v1  armv7f\0" => (Architecture::Arm, false),
            b"dyld_v1  armv7s\0" => (Architecture::Arm, false),
            b"dyld_v1  armv7k\0" => (Architecture::Arm, false),
            b"dyld_v1   arm64\0" => (Architecture::Aarch64, false),
            b"dyld_v1  arm64e\0" => (Architecture::Aarch64, false),
            _ => return Err(Error("Unrecognized dyld cache magic")),
        };
        let endian =
            E::from_big_endian(is_big_endian).read_error("Unsupported dyld cache endian")?;
        Ok((arch, endian))
    }

    /// Return the mapping information table.
    pub fn mappings<'data, R: ReadRef<'data>>(
        &self,
        endian: E,
        data: R,
    ) -> Result<DyldCacheMappingSlice<'data, E>> {
        let header_size = self.mapping_offset.get(endian);
        if header_size >= MIN_HEADER_SIZE_MAPPINGS_V2 {
            let info = data
                .read_slice_at::<macho::DyldCacheMappingAndSlideInfo<E>>(
                    self.mapping_with_slide_offset.get(endian).into(),
                    self.mapping_with_slide_count.get(endian) as usize,
                )
                .read_error("Invalid dyld cache mapping size or alignment")?;
            Ok(DyldCacheMappingSlice::V2(info))
        } else {
            let info = data
                .read_slice_at::<macho::DyldCacheMappingInfo<E>>(
                    self.mapping_offset.get(endian).into(),
                    self.mapping_count.get(endian) as usize,
                )
                .read_error("Invalid dyld cache mapping size or alignment")?;
            Ok(DyldCacheMappingSlice::V1(info))
        }
    }

    /// Return the information about subcaches, if present.
    ///
    /// Returns `None` for dyld caches produced before dyld-940 (macOS 12).
    pub fn subcaches<'data, R: ReadRef<'data>>(
        &self,
        endian: E,
        data: R,
    ) -> Result<Option<DyldSubCacheSlice<'data, E>>> {
        let header_size = self.mapping_offset.get(endian);
        if header_size >= MIN_HEADER_SIZE_SUBCACHES_V2 {
            let subcaches = data
                .read_slice_at::<macho::DyldSubCacheEntryV2<E>>(
                    self.sub_cache_array_offset.get(endian).into(),
                    self.sub_cache_array_count.get(endian) as usize,
                )
                .read_error("Invalid dyld subcaches size or alignment")?;
            Ok(Some(DyldSubCacheSlice::V2(subcaches)))
        } else if header_size >= MIN_HEADER_SIZE_SUBCACHES_V1 {
            let subcaches = data
                .read_slice_at::<macho::DyldSubCacheEntryV1<E>>(
                    self.sub_cache_array_offset.get(endian).into(),
                    self.sub_cache_array_count.get(endian) as usize,
                )
                .read_error("Invalid dyld subcaches size or alignment")?;
            Ok(Some(DyldSubCacheSlice::V1(subcaches)))
        } else {
            Ok(None)
        }
    }

    /// Return the UUID for the .symbols subcache, if present.
    pub fn symbols_subcache_uuid(&self, endian: E) -> Option<[u8; 16]> {
        if self.mapping_offset.get(endian) >= MIN_HEADER_SIZE_SUBCACHES_V1 {
            let uuid = self.symbol_file_uuid;
            if uuid != [0; 16] {
                return Some(uuid);
            }
        }
        None
    }

    /// Return the image information table.
    pub fn images<'data, R: ReadRef<'data>>(
        &self,
        endian: E,
        data: R,
    ) -> Result<&'data [macho::DyldCacheImageInfo<E>]> {
        if self.mapping_offset.get(endian) >= MIN_HEADER_SIZE_SUBCACHES_V1 {
            data.read_slice_at::<macho::DyldCacheImageInfo<E>>(
                self.images_offset.get(endian).into(),
                self.images_count.get(endian) as usize,
            )
            .read_error("Invalid dyld cache image size or alignment")
        } else {
            data.read_slice_at::<macho::DyldCacheImageInfo<E>>(
                self.images_offset_old.get(endian).into(),
                self.images_count_old.get(endian) as usize,
            )
            .read_error("Invalid dyld cache image size or alignment")
        }
    }
}

impl<E: Endian> macho::DyldCacheImageInfo<E> {
    /// The file system path of this image.
    ///
    /// `data` should be the main cache file, not the subcache containing the image.
    pub fn path<'data, R: ReadRef<'data>>(&self, endian: E, data: R) -> Result<&'data [u8]> {
        let r_start = self.path_file_offset.get(endian).into();
        let r_end = data.len().read_error("Couldn't get data len()")?;
        data.read_bytes_at_until(r_start..r_end, 0)
            .read_error("Couldn't read dyld cache image path")
    }
}

impl<E: Endian> macho::DyldCacheMappingAndSlideInfo<E> {
    /// Return the (optional) array of slide information structs
    pub fn slide<'data, R: ReadRef<'data>>(
        &self,
        endian: E,
        data: R,
    ) -> Result<DyldCacheSlideInfo<'data, E>> {
        // TODO: limit further reads to this size?
        if self.slide_info_file_size.get(endian) == 0 {
            return Ok(DyldCacheSlideInfo::None);
        }

        let slide_info_file_offset = self.slide_info_file_offset.get(endian);
        let version = data
            .read_at::<U32<E>>(slide_info_file_offset)
            .read_error("Invalid slide info file offset size or alignment")?
            .get(endian);
        match version {
            2 => {
                let slide = data
                    .read_at::<macho::DyldCacheSlideInfo2<E>>(slide_info_file_offset)
                    .read_error("Invalid dyld cache slide info offset or alignment")?;
                let page_starts_offset = slide_info_file_offset
                    .checked_add(slide.page_starts_offset.get(endian) as u64)
                    .read_error("Invalid dyld cache page starts offset")?;
                let page_starts = data
                    .read_slice_at::<U16<E>>(
                        page_starts_offset,
                        slide.page_starts_count.get(endian) as usize,
                    )
                    .read_error("Invalid dyld cache page starts size or alignment")?;
                let page_extras_offset = slide_info_file_offset
                    .checked_add(slide.page_extras_offset.get(endian) as u64)
                    .read_error("Invalid dyld cache page extras offset")?;
                let page_extras = data
                    .read_slice_at::<U16<E>>(
                        page_extras_offset,
                        slide.page_extras_count.get(endian) as usize,
                    )
                    .read_error("Invalid dyld cache page extras size or alignment")?;
                Ok(DyldCacheSlideInfo::V2 {
                    slide,
                    page_starts,
                    page_extras,
                })
            }
            3 => {
                let slide = data
                    .read_at::<macho::DyldCacheSlideInfo3<E>>(slide_info_file_offset)
                    .read_error("Invalid dyld cache slide info offset or alignment")?;
                let page_starts_offset = slide_info_file_offset
                    .checked_add(mem::size_of::<macho::DyldCacheSlideInfo3<E>>() as u64)
                    .read_error("Invalid dyld cache page starts offset")?;
                let page_starts = data
                    .read_slice_at::<U16<E>>(
                        page_starts_offset,
                        slide.page_starts_count.get(endian) as usize,
                    )
                    .read_error("Invalid dyld cache page starts size or alignment")?;
                Ok(DyldCacheSlideInfo::V3 { slide, page_starts })
            }
            5 => {
                let slide = data
                    .read_at::<macho::DyldCacheSlideInfo5<E>>(slide_info_file_offset)
                    .read_error("Invalid dyld cache slide info offset or alignment")?;
                let page_starts_offset = slide_info_file_offset
                    .checked_add(mem::size_of::<macho::DyldCacheSlideInfo5<E>>() as u64)
                    .read_error("Invalid dyld cache page starts offset")?;
                let page_starts = data
                    .read_slice_at::<U16<E>>(
                        page_starts_offset,
                        slide.page_starts_count.get(endian) as usize,
                    )
                    .read_error("Invalid dyld cache page starts size or alignment")?;
                Ok(DyldCacheSlideInfo::V5 { slide, page_starts })
            }
            _ => Err(Error("Unsupported dyld cache slide info version")),
        }
    }
}