ld-so-cache 0.1.0

A parser for glibc ld.so.cache files
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

//! # ld.so.cache Parser Library
//!
//! This crate provides a comprehensive parser for `ld.so.cache` files used by the Linux dynamic linker.
//! It supports both the legacy format (ld.so-1.7.0) and the modern glibc format with hardware capabilities.
//!
//! ## Quick Start
//!
//! ```rust
//! use ld_so_cache::parsers::parse_ld_cache;
//! use std::fs;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Parse the system's ld.so.cache file
//! let data = fs::read("/etc/ld.so.cache")?;
//! let cache = parse_ld_cache(&data)?;
//!
//! // Extract all library entries
//! let entries = cache.get_entries()?;
//! for entry in entries {
//!     println!("{} -> {}", entry.library_name, entry.library_path);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Cache Formats
//!
//! The library supports two cache formats:
//!
//! - **Old Format**: Used by ld.so-1.7.0, contains basic library mappings
//! - **New Format**: Used by glibc, includes hardware capabilities and extensions
//!
//! ## Hardware Capabilities
//!
//! The new format includes hardware capability flags that indicate processor features
//! required by libraries. This allows the dynamic linker to select the most optimized
//! version of a library for the current processor.
//!
//! ### Hardware Capability Bits
//!
//! The 64-bit `hwcap` field encodes various processor features:
//!
//! ```rust
//! # use ld_so_cache::NewFileEntry;
//! let entry = NewFileEntry {
//!     flags: 1,
//!     key: 0,
//!     value: 10,
//!     osversion_unused: 0,
//!     hwcap: 0x0002000000000000, // Example capability
//! };
//!
//! // Extract ISA level (bits 52-61)
//! let isa_level = (entry.hwcap >> 52) & 0x3ff;
//! if isa_level >= 2 {
//!     println!("Requires x86-64-v2 or higher");
//! }
//!
//! // Check for extension flag (bit 62)
//! let has_extensions = entry.hwcap & (1u64 << 62) != 0;
//! if has_extensions {
//!     println!("Library uses hardware capability extensions");
//! }
//!
//! // Check for specific CPU features (bits 0-51)
//! // Note: Exact bit meanings are architecture-specific
//! let cpu_features = entry.hwcap & ((1u64 << 52) - 1);
//! ```
//!
//! ## Error Handling
//!
//! All parsing operations return `Result<T, CacheError>` for robust error handling.
//! The library is designed to be resilient and will attempt to extract as much
//! information as possible even from partially corrupted files.
//!
//! ### Common Error Patterns
//!
//! ```rust
//! use ld_so_cache::{parsers::parse_ld_cache, CacheError};
//! use std::fs;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Read and parse cache file
//! let data = fs::read("/etc/ld.so.cache")?;
//! match parse_ld_cache(&data) {
//!     Ok(cache) => {
//!         // Successfully parsed cache
//!         match cache.get_entries() {
//!             Ok(entries) => println!("Found {} libraries", entries.len()),
//!             Err(CacheError::InvalidStringOffset(offset)) => {
//!                 eprintln!("Corrupted string table at offset {}", offset);
//!             }
//!             Err(e) => eprintln!("Error extracting entries: {}", e),
//!         }
//!     }
//!     Err(CacheError::InvalidMagic) => {
//!         eprintln!("File is not a valid ld.so.cache");
//!     }
//!     Err(CacheError::TruncatedFile) => {
//!         eprintln!("Cache file appears to be truncated");
//!     }
//!     Err(e) => eprintln!("Parse error: {}", e),
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### Graceful Degradation
//!
//! When extracting entries, the library skips invalid entries rather than failing:
//!
//! ```rust
//! # use ld_so_cache::parsers::parse_ld_cache;
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let data = vec![]; // Would be actual cache data
//! let cache = parse_ld_cache(&data)?;
//! let entries = cache.get_entries()?; // Will skip invalid entries
//! 
//! // Even if some entries are corrupted, we get the valid ones
//! for entry in entries {
//!     println!("{} -> {}", entry.library_name, entry.library_path);
//! }
//! # Ok(())
//! # }
//! ```

/// The main cache structure representing a parsed `ld.so.cache` file.
///
/// This structure can contain either the old format, new format, or both.
/// When both formats are present, the new format takes precedence for library lookups.
///
/// # Fields
///
/// * `old_format` - Legacy cache format data (ld.so-1.7.0)
/// * `new_format` - Modern glibc cache format with hardware capabilities
/// * `string_table` - Raw bytes containing null-terminated library names and paths
/// * `string_table_offset` - Absolute file offset where the string table begins (for new format)
///
/// # Examples
///
/// ```rust
/// use ld_so_cache::parsers::parse_ld_cache;
/// # use std::fs;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let data = fs::read("/etc/ld.so.cache")?;
/// let cache = parse_ld_cache(&data)?;
///
/// // Check which formats are present
/// if cache.old_format.is_some() {
///     println!("Old format present");
/// }
/// if cache.new_format.is_some() {
///     println!("New format present");
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct LdCache {
    pub old_format: Option<OldCache>,
    pub new_format: Option<NewCache>,
    pub string_table: Vec<u8>,
    pub string_table_offset: usize,
}

/// Legacy cache format used by ld.so-1.7.0.
///
/// This format provides basic library name to path mappings without
/// hardware capability information.
///
/// # Fields
///
/// * `nlibs` - Number of library entries in the cache
/// * `entries` - Vector of old format file entries
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::OldCache;
/// let old_cache = OldCache {
///     nlibs: 10,
///     entries: vec![], // Would contain actual entries
/// };
/// assert_eq!(old_cache.nlibs, 10);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct OldCache {
    pub nlibs: u32,
    pub entries: Vec<OldFileEntry>,
}

/// A single library entry in the old cache format.
///
/// # Fields
///
/// * `flags` - Library type flags (bit 0: ELF library)
/// * `key` - Offset into string table for library name
/// * `value` - Offset into string table for library path
///
/// # Flag Values
///
/// * `flags & 1 != 0` - ELF library
/// * `flags & 1 == 0` - Other/unknown format
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::OldFileEntry;
/// let entry = OldFileEntry {
///     flags: 1,  // ELF library
///     key: 0,    // Library name at offset 0 in string table
///     value: 10, // Library path at offset 10 in string table
/// };
/// assert!(entry.flags & 1 != 0); // Is ELF library
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct OldFileEntry {
    pub flags: i32,
    pub key: u32,
    pub value: u32,
}

/// Modern glibc cache format with hardware capabilities and extensions.
///
/// This format extends the old format with hardware capability matching
/// and optional extension directories for future enhancements.
///
/// # Fields
///
/// * `nlibs` - Number of library entries in the cache
/// * `len_strings` - Length of the string table in bytes
/// * `flags` - Endianness and format flags (2 = little endian)
/// * `extension_offset` - File offset to extension directory (0 = none)
/// * `entries` - Vector of new format file entries with hardware capabilities
/// * `extensions` - Optional extension directory for additional metadata
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::NewCache;
/// let new_cache = NewCache {
///     nlibs: 100,
///     len_strings: 5000,
///     flags: 2, // Little endian
///     extension_offset: 0, // No extensions
///     entries: vec![],
///     extensions: None,
/// };
/// assert_eq!(new_cache.flags, 2);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct NewCache {
    pub nlibs: u32,
    pub len_strings: u32,
    pub flags: u8,
    pub extension_offset: u32,
    pub entries: Vec<NewFileEntry>,
    pub extensions: Option<ExtensionDirectory>,
}

/// A single library entry in the new cache format with hardware capabilities.
///
/// # Fields
///
/// * `flags` - Library type flags (same as old format)
/// * `key` - Offset into string table for library name
/// * `value` - Offset into string table for library path
/// * `osversion_unused` - Unused field (always 0)
/// * `hwcap` - Hardware capability mask indicating required processor features
///
/// # Hardware Capabilities
///
/// The `hwcap` field encodes processor features required by the library:
/// * Bits 0-51: Various CPU features (SSE, AVX, etc.)
/// * Bits 52-61: ISA level (x86-64-v2, x86-64-v3, etc.)
/// * Bit 62: Extension flag
/// * Bit 63: Reserved
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::NewFileEntry;
/// let entry = NewFileEntry {
///     flags: 1,
///     key: 0,
///     value: 20,
///     osversion_unused: 0,
///     hwcap: 0x1000000000000000, // Some capability set
/// };
/// 
/// // Check for extension flag
/// let has_extension = entry.hwcap & (1u64 << 62) != 0;
/// 
/// // Extract ISA level
/// let isa_level = (entry.hwcap >> 52) & 0x3ff;
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct NewFileEntry {
    pub flags: i32,
    pub key: u32,
    pub value: u32,
    pub osversion_unused: u32,
    pub hwcap: u64,
}

/// Directory of extension sections for future cache format enhancements.
///
/// This allows the cache format to be extended with additional metadata
/// while maintaining backward compatibility.
///
/// # Fields
///
/// * `count` - Number of extension sections
/// * `sections` - Vector of extension section descriptors
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::{ExtensionDirectory, ExtensionSection};
/// let ext_dir = ExtensionDirectory {
///     count: 2,
///     sections: vec![
///         ExtensionSection { tag: 1, flags: 0, offset: 100, size: 50 },
///         ExtensionSection { tag: 2, flags: 0, offset: 150, size: 30 },
///     ],
/// };
/// assert_eq!(ext_dir.count, 2);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ExtensionDirectory {
    pub count: u32,
    pub sections: Vec<ExtensionSection>,
}

/// A single extension section descriptor.
///
/// Extension sections allow for future enhancements to the cache format
/// without breaking existing parsers.
///
/// # Fields
///
/// * `tag` - Identifies the type of extension data
/// * `flags` - Extension-specific flags
/// * `offset` - File offset where extension data begins
/// * `size` - Size of extension data in bytes
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::ExtensionSection;
/// let section = ExtensionSection {
///     tag: 1,      // Extension type 1
///     flags: 0,    // No special flags
///     offset: 1000, // Data starts at offset 1000
///     size: 256,   // 256 bytes of data
/// };
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ExtensionSection {
    pub tag: u32,
    pub flags: u32,
    pub offset: u32,
    pub size: u32,
}

/// Represents the different cache format combinations that can be found.
///
/// Real-world cache files may contain only the old format, only the new format,
/// or both formats for backward compatibility.
///
/// # Variants
///
/// * `OldOnly` - File contains only the legacy ld.so-1.7.0 format
/// * `NewOnly` - File contains only the modern glibc format
/// * `Both` - File contains both formats (common for compatibility)
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::{CacheFormat, OldCache, NewCache};
/// # let old_cache = OldCache { nlibs: 0, entries: vec![] };
/// # let new_cache = NewCache { nlibs: 0, len_strings: 0, flags: 2, extension_offset: 0, entries: vec![], extensions: None };
/// let format = CacheFormat::Both {
///     old: old_cache,
///     new: new_cache,
/// };
/// 
/// match format {
///     CacheFormat::OldOnly(_) => println!("Legacy format only"),
///     CacheFormat::NewOnly(_) => println!("Modern format only"),
///     CacheFormat::Both { .. } => println!("Both formats present"),
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum CacheFormat {
    OldOnly(OldCache),
    NewOnly(NewCache),
    Both { old: OldCache, new: NewCache },
}

/// A processed library entry extracted from the cache.
///
/// This represents a single library mapping with resolved strings and
/// optional hardware capability information.
///
/// # Fields
///
/// * `library_name` - The library name (e.g., "libc.so.6")
/// * `library_path` - Full path to the library file
/// * `flags` - Library type flags (bit 0: ELF library)
/// * `hwcap` - Hardware capabilities (None for old format entries)
///
/// # Serialization
///
/// When serialized to JSON, hardware capabilities are formatted as
/// hexadecimal strings (e.g., "0x0000000000001000").
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::CacheEntry;
/// let entry = CacheEntry {
///     library_name: "libc.so.6".to_string(),
///     library_path: "/lib/x86_64-linux-gnu/libc.so.6".to_string(),
///     flags: 1, // ELF library
///     hwcap: Some(0x1000), // Some hardware capability
/// };
/// 
/// // Check if it's an ELF library
/// let is_elf = entry.flags & 1 != 0;
/// assert!(is_elf);
/// 
/// // Check for hardware capabilities
/// if let Some(hwcap) = entry.hwcap {
///     println!("Hardware capabilities: 0x{:016x}", hwcap);
/// }
/// ```
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct CacheEntry {
    pub library_name: String,
    pub library_path: String,
    pub flags: i32,
    #[serde(with = "hwcap_format", skip_serializing_if = "Option::is_none")]
    pub hwcap: Option<u64>,
}

mod hwcap_format {
    use serde::{Serializer, Serialize};

    pub fn serialize<S>(hwcap: &Option<u64>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match hwcap {
            Some(value) => format!("0x{value:016x}").serialize(serializer),
            None => serializer.serialize_none(),
        }
    }
}

impl LdCache {
    /// Extracts all library entries from the cache.
    ///
    /// This method processes both old and new format entries, converting raw
    /// cache data into user-friendly `CacheEntry` structures. If both formats
    /// are present, only the new format entries are returned as they include
    /// hardware capability information.
    ///
    /// # Returns
    ///
    /// A vector of `CacheEntry` structures containing library names, paths,
    /// flags, and hardware capabilities (when available).
    ///
    /// # Errors
    ///
    /// * `CacheError::InvalidStringOffset` - String offset points outside the string table
    /// * `CacheError::ParseError` - String contains invalid UTF-8 characters
    ///
    /// Invalid entries are silently skipped rather than causing the entire
    /// operation to fail.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use ld_so_cache::parsers::parse_ld_cache;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let data = vec![]; // Would be actual cache data
    /// # let cache = parse_ld_cache(&data)?;
    /// let entries = cache.get_entries()?;
    /// 
    /// for entry in entries {
    ///     println!("{} -> {}", entry.library_name, entry.library_path);
    ///     
    ///     if entry.flags & 1 != 0 {
    ///         println!("  ELF library");
    ///     }
    ///     
    ///     if let Some(hwcap) = entry.hwcap {
    ///         println!("  Hardware capabilities: 0x{:016x}", hwcap);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_entries(&self) -> Result<Vec<CacheEntry>, CacheError> {
        let string_table = &self.string_table;
        let mut entries = Vec::new();

        if let Some(new_cache) = &self.new_format {
            for entry in &new_cache.entries {
                // For new format, offsets might be absolute file offsets
                let key_offset = if self.string_table_offset > 0 && entry.key as usize >= self.string_table_offset {
                    entry.key as usize - self.string_table_offset
                } else {
                    entry.key as usize
                };
                
                let value_offset = if self.string_table_offset > 0 && entry.value as usize >= self.string_table_offset {
                    entry.value as usize - self.string_table_offset
                } else {
                    entry.value as usize
                };
                
                if key_offset >= string_table.len() || value_offset >= string_table.len() {
                    continue; // Skip invalid entries instead of failing
                }
                
                let name = extract_string(string_table, key_offset)?;
                let path = extract_string(string_table, value_offset)?;
                entries.push(CacheEntry {
                    library_name: name,
                    library_path: path,
                    flags: entry.flags,
                    hwcap: Some(entry.hwcap),
                });
            }
        } else if let Some(old_cache) = &self.old_format {
            for entry in &old_cache.entries {
                if entry.key as usize >= string_table.len() || entry.value as usize >= string_table.len() {
                    continue; // Skip invalid entries instead of failing
                }
                let name = extract_string(string_table, entry.key as usize)?;
                let path = extract_string(string_table, entry.value as usize)?;
                entries.push(CacheEntry {
                    library_name: name,
                    library_path: path,
                    flags: entry.flags,
                    hwcap: None,
                });
            }
        }

        Ok(entries)
    }
}

/// Errors that can occur during cache parsing and processing.
///
/// This enum covers all possible failure modes when parsing `ld.so.cache` files,
/// from file format issues to data corruption.
///
/// # Variants
///
/// * `ParseError` - Generic parsing failure with descriptive message
/// * `InvalidStringOffset` - String offset points outside the string table
/// * `InvalidMagic` - File doesn't start with a recognized magic number
/// * `TruncatedFile` - File is too short to contain valid cache data
/// * `InvalidEndianness` - Unsupported byte order in cache file
///
/// # Example
///
/// ```rust
/// # use ld_so_cache::{CacheError, parsers::parse_ld_cache};
/// let invalid_data = b"not a cache file";
/// let result = parse_ld_cache(invalid_data);
/// 
/// match result {
///     Err(CacheError::InvalidMagic) => {
///         println!("File is not a valid ld.so.cache");
///     }
///     Err(CacheError::TruncatedFile) => {
///         println!("Cache file is incomplete");
///     }
///     Err(e) => println!("Other error: {}", e),
///     Ok(_) => println!("Successfully parsed"),
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum CacheError {
    /// Generic parsing error with descriptive message
    ParseError(String),
    /// String offset points beyond the string table bounds
    InvalidStringOffset(usize),
    /// File doesn't begin with a recognized magic number
    InvalidMagic,
    /// File is too short to contain required cache structures
    TruncatedFile,
    /// Cache uses unsupported byte order
    InvalidEndianness,
}

impl std::fmt::Display for CacheError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CacheError::ParseError(msg) => write!(f, "Parse error: {msg}"),
            CacheError::InvalidStringOffset(offset) => write!(f, "Invalid string offset: {offset}"),
            CacheError::InvalidMagic => write!(f, "Invalid magic number"),
            CacheError::TruncatedFile => write!(f, "Truncated file"),
            CacheError::InvalidEndianness => write!(f, "Invalid endianness"),
        }
    }
}

impl std::error::Error for CacheError {}

fn extract_string(string_table: &[u8], offset: usize) -> Result<String, CacheError> {
    if offset >= string_table.len() {
        return Err(CacheError::InvalidStringOffset(offset));
    }

    let slice = &string_table[offset..];
    let null_pos = slice
        .iter()
        .position(|&b| b == 0)
        .ok_or(CacheError::InvalidStringOffset(offset))?;

    String::from_utf8(slice[..null_pos].to_vec())
        .map_err(|_| CacheError::ParseError("Invalid UTF-8 in string".to_string()))
}

pub mod parsers;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsers::parse_ld_cache;

    #[test]
    fn test_extract_string() {
        let string_table = b"hello\0world\0test\0";
        
        assert_eq!(extract_string(string_table, 0).unwrap(), "hello");
        assert_eq!(extract_string(string_table, 6).unwrap(), "world");
        assert_eq!(extract_string(string_table, 12).unwrap(), "test");
        
        assert!(extract_string(string_table, 100).is_err());
    }

    #[test]
    fn test_extract_string_edge_cases() {
        let string_table = b"a\0";
        assert_eq!(extract_string(string_table, 0).unwrap(), "a");
        
        let empty_string_table = b"\0";
        assert_eq!(extract_string(empty_string_table, 0).unwrap(), "");
        
        let no_null_terminator = b"hello";
        assert!(extract_string(no_null_terminator, 0).is_err());
        
        let string_table = b"hello\0";
        assert!(extract_string(string_table, 10).is_err());
    }

    #[test]
    fn test_cache_entry_creation() {
        let entry = CacheEntry {
            library_name: "libc.so.6".to_string(),
            library_path: "/lib/x86_64-linux-gnu/libc.so.6".to_string(),
            flags: 1,
            hwcap: Some(0x1234_5678),
        };
        
        assert_eq!(entry.library_name, "libc.so.6");
        assert_eq!(entry.flags, 1);
        assert_eq!(entry.hwcap, Some(0x1234_5678));
    }

    #[test]
    fn test_parse_old_format_cache() {
        let mut data = Vec::new();
        
        data.extend_from_slice(b"ld.so-1.7.0");
        data.extend_from_slice(&2u32.to_le_bytes());
        
        data.extend_from_slice(&1i32.to_le_bytes());
        data.extend_from_slice(&0u32.to_le_bytes());
        data.extend_from_slice(&10u32.to_le_bytes());
        
        data.extend_from_slice(&1i32.to_le_bytes());
        data.extend_from_slice(&20u32.to_le_bytes());
        data.extend_from_slice(&40u32.to_le_bytes());
        
        data.extend_from_slice(b"libc.so.6\0/lib/libc.so.6\0libm.so.6\0/lib/libm.so.6\0");
        
        let cache = parse_ld_cache(&data).unwrap();
        assert!(cache.old_format.is_some());
        assert!(cache.new_format.is_none());
        
        let old_cache = cache.old_format.as_ref().unwrap();
        assert_eq!(old_cache.nlibs, 2);
        assert_eq!(old_cache.entries.len(), 2);
        assert_eq!(old_cache.entries[0].flags, 1);
        assert_eq!(old_cache.entries[0].key, 0);
        assert_eq!(old_cache.entries[0].value, 10);
        
        let entries = cache.get_entries().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].library_name, "libc.so.6");
        assert_eq!(entries[0].library_path, "/lib/libc.so.6");
        assert!(entries[0].hwcap.is_none());
    }

    #[test]
    fn test_parse_new_format_cache() {
        let mut data = Vec::new();
        
        data.extend_from_slice(b"glibc-ld.so.cache");
        data.extend_from_slice(b"1.1");
        data.extend_from_slice(&1u32.to_le_bytes());
        data.extend_from_slice(&30u32.to_le_bytes());
        data.push(2);
        data.extend_from_slice(&[0, 0, 0]);
        data.extend_from_slice(&0u32.to_le_bytes());
        data.extend_from_slice(&[0; 12]);
        
        data.extend_from_slice(&1i32.to_le_bytes());
        data.extend_from_slice(&0u32.to_le_bytes());
        data.extend_from_slice(&10u32.to_le_bytes());
        data.extend_from_slice(&0u32.to_le_bytes());
        data.extend_from_slice(&0x1234_5678_u64.to_le_bytes());
        
        data.extend_from_slice(b"libc.so.6\0/lib/libc.so.6\0");
        
        let cache = parse_ld_cache(&data).unwrap();
        assert!(cache.new_format.is_some());
        assert!(cache.old_format.is_none());
        
        let new_cache = cache.new_format.as_ref().unwrap();
        assert_eq!(new_cache.nlibs, 1);
        assert_eq!(new_cache.len_strings, 30);
        assert_eq!(new_cache.flags, 2);
        assert_eq!(new_cache.entries.len(), 1);
        assert_eq!(new_cache.entries[0].hwcap, 0x1234_5678);
        
        let entries = cache.get_entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].library_name, "libc.so.6");
        assert_eq!(entries[0].library_path, "/lib/libc.so.6");
        assert_eq!(entries[0].hwcap, Some(0x1234_5678));
    }

    #[test]
    fn test_parse_invalid_magic() {
        let invalid_data = b"invalid-magic-that-is-long-enough";
        let result = parse_ld_cache(invalid_data);
        assert!(matches!(result, Err(CacheError::InvalidMagic)));
    }

    #[test]
    fn test_parse_truncated_file() {
        let truncated_data = b"ld.so-1.7.0";
        let result = parse_ld_cache(truncated_data);
        assert!(matches!(result, Err(CacheError::TruncatedFile)));
    }

    #[test]
    fn test_cache_error_display() {
        let error = CacheError::ParseError("test error".to_string());
        assert_eq!(format!("{error}"), "Parse error: test error");
        
        let error = CacheError::InvalidStringOffset(42);
        assert_eq!(format!("{error}"), "Invalid string offset: 42");
        
        let error = CacheError::InvalidMagic;
        assert_eq!(format!("{error}"), "Invalid magic number");
        
        let error = CacheError::TruncatedFile;
        assert_eq!(format!("{error}"), "Truncated file");
        
        let error = CacheError::InvalidEndianness;
        assert_eq!(format!("{error}"), "Invalid endianness");
    }

    #[test]
    fn test_empty_cache() {
        let mut data = Vec::new();
        data.extend_from_slice(b"ld.so-1.7.0");
        data.extend_from_slice(&0u32.to_le_bytes());
        
        let cache = parse_ld_cache(&data).unwrap();
        let entries = cache.get_entries().unwrap();
        assert_eq!(entries.len(), 0);
    }

    #[test]
    fn test_ld_cache_get_entries_preference() {
        let old_cache = OldCache {
            nlibs: 1,
            entries: vec![OldFileEntry {
                flags: 1,
                key: 0,
                value: 10,
            }],
        };
        
        let new_cache = NewCache {
            nlibs: 1,
            len_strings: 30,
            flags: 2,
            extension_offset: 0,
            entries: vec![NewFileEntry {
                flags: 1,
                key: 0,
                value: 10,
                osversion_unused: 0,
                hwcap: 0x1234_5678,
            }],
            extensions: None,
        };
        
        let string_table = b"libc.so.6\0/lib/libc.so.6\0".to_vec();
        
        let cache_with_both = LdCache {
            old_format: Some(old_cache),
            new_format: Some(new_cache),
            string_table: string_table.clone(),
            string_table_offset: 0,
        };
        
        let entries = cache_with_both.get_entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].hwcap, Some(0x1234_5678));
    }

    #[test]
    fn test_hwcap_bit_decoding() {
        // Test ISA level extraction (bits 52-61)
        let hwcap_with_isa_v2: u64 = 2u64 << 52;
        let isa_level = (hwcap_with_isa_v2 >> 52) & 0x3ff;
        assert_eq!(isa_level, 2);
        
        let hwcap_with_isa_v3: u64 = 3u64 << 52;
        let isa_level = (hwcap_with_isa_v3 >> 52) & 0x3ff;
        assert_eq!(isa_level, 3);
        
        // Test extension flag (bit 62)
        let hwcap_with_extension: u64 = 1u64 << 62;
        assert!(hwcap_with_extension & (1u64 << 62) != 0);
        
        let hwcap_without_extension: u64 = 0x0000_1234_5678_9ABC;
        assert!(hwcap_without_extension & (1u64 << 62) == 0);
        
        // Test CPU features mask (bits 0-51)
        let hwcap_with_features: u64 = 0x000F_FFFF_FFFF_FFFF; // All feature bits set
        let cpu_features = hwcap_with_features & ((1u64 << 52) - 1);
        assert_eq!(cpu_features, 0x000F_FFFF_FFFF_FFFF);
        
        // Test combined hwcap
        let entry = NewFileEntry {
            flags: 1,
            key: 0,
            value: 0,
            osversion_unused: 0,
            hwcap: 0x0020_0000_0000_1234, // ISA level 2 (2 << 52) + some features
        };
        
        let isa_level = (entry.hwcap >> 52) & 0x3ff;
        let features = entry.hwcap & ((1u64 << 52) - 1);
        
        assert_eq!(isa_level, 2);
        assert_eq!(features, 0x1234);
        
        // Test with extension flag
        let entry_with_ext = NewFileEntry {
            flags: 1,
            key: 0,
            value: 0,
            osversion_unused: 0,
            hwcap: 0x4000_0000_0000_0000, // Just extension flag
        };
        
        let has_extension = entry_with_ext.hwcap & (1u64 << 62) != 0;
        assert!(has_extension);
    }

    #[test]
    fn test_graceful_degradation_with_invalid_entries() {
        // Create cache with mix of valid and invalid entries
        let new_cache = NewCache {
            nlibs: 4,
            len_strings: 50,
            flags: 2,
            extension_offset: 0,
            entries: vec![
                NewFileEntry {
                    flags: 1,
                    key: 0,
                    value: 10,
                    osversion_unused: 0,
                    hwcap: 0x1234,
                },
                NewFileEntry {
                    flags: 1,
                    key: 1000, // Invalid offset
                    value: 2000, // Invalid offset
                    osversion_unused: 0,
                    hwcap: 0x5678,
                },
                NewFileEntry {
                    flags: 1,
                    key: 26,
                    value: 36,
                    osversion_unused: 0,
                    hwcap: 0x9ABC,
                },
                NewFileEntry {
                    flags: 1,
                    key: 500, // Invalid offset
                    value: 10,
                    osversion_unused: 0,
                    hwcap: 0xDEF0,
                },
            ],
            extensions: None,
        };
        
        let string_table = b"libc.so.6\0/lib/libc.so.6\0\0libm.so.6\0/lib/libm.so.6\0".to_vec();
        
        let cache = LdCache {
            old_format: None,
            new_format: Some(new_cache),
            string_table,
            string_table_offset: 0,
        };
        
        // Should skip invalid entries and return only valid ones
        let entries = cache.get_entries().unwrap();
        assert_eq!(entries.len(), 2); // Only 2 valid entries
        assert_eq!(entries[0].library_name, "libc.so.6");
        assert_eq!(entries[1].library_name, "libm.so.6");
    }

    #[test]
    fn test_string_table_offset_adjustment() {
        // Test with absolute file offsets
        let new_cache = NewCache {
            nlibs: 1,
            len_strings: 30,
            flags: 2,
            extension_offset: 0,
            entries: vec![NewFileEntry {
                flags: 1,
                key: 1000, // Absolute offset
                value: 1010, // Absolute offset
                osversion_unused: 0,
                hwcap: 0x1234,
            }],
            extensions: None,
        };
        
        let string_table = b"libc.so.6\0/lib/libc.so.6\0".to_vec();
        
        let cache = LdCache {
            old_format: None,
            new_format: Some(new_cache),
            string_table,
            string_table_offset: 1000, // String table starts at offset 1000
        };
        
        let entries = cache.get_entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].library_name, "libc.so.6");
        assert_eq!(entries[0].library_path, "/lib/libc.so.6");
    }

    #[test]
    fn test_flags_architecture_decoding() {
        // Test i386 (arch bits = 0)
        let i386_flags = 0x0001; // ELF + arch 0
        let arch_bits = (i386_flags >> 8) & 0xf;
        assert_eq!(arch_bits, 0);
        
        // Test x86_64 (arch bits = 3)
        let x86_64_flags = 0x0301; // ELF + arch 3
        let arch_bits = (x86_64_flags >> 8) & 0xf;
        assert_eq!(arch_bits, 3);
        
        // Test libx32 (arch bits = 8)
        let libx32_flags = 0x0801; // ELF + arch 8
        let arch_bits = (libx32_flags >> 8) & 0xf;
        assert_eq!(arch_bits, 8);
    }

    #[test]
    fn test_endianness_flag_values() {
        // Test all documented flag values
        let test_cases = vec![
            (0u8, "Endianness unset (legacy)"),
            (1u8, "Invalid cache"),
            (2u8, "Little endian"),
            (3u8, "Big endian"),
        ];
        
        for (flag_value, expected_meaning) in test_cases {
            let new_cache = NewCache {
                nlibs: 0,
                len_strings: 0,
                flags: flag_value,
                extension_offset: 0,
                entries: vec![],
                extensions: None,
            };
            
            // Verify the flag value is stored correctly
            assert_eq!(new_cache.flags, flag_value);
            
            // Verify the meaning matches documentation
            let meaning = match flag_value {
                0 => "Endianness unset (legacy)",
                1 => "Invalid cache",
                2 => "Little endian",
                3 => "Big endian",
                _ => "Unknown",
            };
            assert_eq!(meaning, expected_meaning);
        }
    }

    #[test]
    fn test_extension_tag_meanings() {
        let ext_dir = ExtensionDirectory {
            count: 2,
            sections: vec![
                ExtensionSection {
                    tag: 1,
                    flags: 0,
                    offset: 100,
                    size: 50,
                },
                ExtensionSection {
                    tag: 2,
                    flags: 0,
                    offset: 150,
                    size: 30,
                },
            ],
        };
        
        // Verify tag meanings as documented
        assert_eq!(ext_dir.sections[0].tag, 1); // cache_extension_tag_generator
        assert_eq!(ext_dir.sections[1].tag, 2); // cache_extension_tag_glibc_hwcaps
    }

    #[test]
    fn test_cache_entry_serialization_with_hwcap() {
        let entry = CacheEntry {
            library_name: "libc.so.6".to_string(),
            library_path: "/lib/x86_64-linux-gnu/libc.so.6".to_string(),
            flags: 0x0301, // x86_64 ELF
            hwcap: Some(0x0000_0000_0000_1000),
        };
        
        // Serialize to JSON
        let json = serde_json::to_string(&entry).unwrap();
        
        // Verify hwcap is formatted as hex string
        assert!(json.contains("\"hwcap\":\"0x0000000000001000\""));
        
        // Test without hwcap
        let entry_no_hwcap = CacheEntry {
            library_name: "libm.so.6".to_string(),
            library_path: "/lib/libm.so.6".to_string(),
            flags: 1,
            hwcap: None,
        };
        
        let json_no_hwcap = serde_json::to_string(&entry_no_hwcap).unwrap();
        assert!(!json_no_hwcap.contains("hwcap"));
    }
}