dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
//! Metadata root header and stream directory for .NET assemblies.
//!
//! This module defines the [`crate::metadata::root::Root`] struct, which represents the root metadata header and stream
//! directory as specified by ECMA-335. It provides access to all metadata streams, version info,
//! and structural metadata required for parsing .NET assemblies.
//!
//! # Overview
//!
//! The metadata root is the entry point for reading .NET assembly metadata. It contains the version
//! string, stream directory, and other header fields required to locate and interpret all metadata
//! streams (such as `#~`, `#Strings`, `#Blob`, etc.).
//!
//! # Example
//!
//! ```rust,no_run
//! use dotscope::metadata::root::Root;
//! let root = Root::read(&[
//!            0x42, 0x53, 0x4A, 0x42,
//!            0x00, 0x20,
//!            0x00, 0x30,
//!            0x00, 0x00, 0x00, 0x40,
//!            0x05, 0x00, 0x00, 0x00,
//!            b'H', b'E', b'L', b'L', b'O',
//!            0x00, 0x60,
//!            0x01, 0x00,
//!            0x1, 0x00, 0x00, 0x00, // StreamHeader
//!            0x5, 0x00, 0x00, 0x00,
//!            0x23, 0x7E, 0x00,
//!        ])?;
//! println!("Metadata version: {}", root.version);
//! for stream in &root.stream_headers {
//!     println!("Stream: {} (offset: {}, size: {})", stream.name, stream.offset, stream.size);
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # References
//!
//! - [ECMA-335 II.24.2.1: Metadata root](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf)

use crate::{
    metadata::streams::StreamHeader,
    utils::{read_le, read_le_at},
    Result,
};
use std::io::Write;

/// The MAGIC value indicating the CIL header ("BSJB" in ASCII).
pub const CIL_HEADER_MAGIC: u32 = 0x424A_5342;

/// Minimum size in bytes required for a valid metadata root header.
/// This includes: signature(4) + major_version(2) + minor_version(2) + reserved(4) +
/// length(4) + version_string(min 4) + flags(2) + stream_number(2) + stream_header(min 12).
const MIN_ROOT_HEADER_SIZE: usize = 36;

/// Offset in the root header where the version string length field is located.
const VERSION_LENGTH_OFFSET: usize = 12;

/// Offset in the root header where the version string begins.
const VERSION_STRING_OFFSET: u16 = 16;

/// Size of the flags field following the version string.
const FLAGS_FIELD_SIZE: usize = 2;

/// Size of the stream count field.
const STREAM_COUNT_FIELD_SIZE: usize = 2;

/// Maximum allowed length for the version string.
const MAX_VERSION_STRING_LENGTH: usize = 255;

/// Maximum number of metadata streams allowed per ECMA-335.
/// Valid streams are: #Strings, #US, #Blob, #GUID, #~, #-
const MAX_STREAM_COUNT: u16 = 6;

/// Minimum size in bytes for a valid stream header.
/// This includes: offset(4) + size(4) + name(min 1 char + null terminator = 2, aligned to 4).
const MIN_STREAM_HEADER_SIZE: usize = 12;

/// Size of the fixed fields in a stream header (offset + size).
const STREAM_HEADER_FIXED_SIZE: usize = 8;

/// Maximum length for a stream name.
const MAX_STREAM_NAME_LENGTH: usize = 32;

/// Field offsets within the root header for fixed-position fields.
const FIELD_OFFSET_MAJOR_VERSION: usize = 4;
const FIELD_OFFSET_MINOR_VERSION: usize = 6;
const FIELD_OFFSET_RESERVED: usize = 8;

/// Represents the metadata root header and stream directory of a .NET assembly.
///
/// The Root structure is the entry point for all .NET assembly metadata parsing, containing
/// the metadata header information and directory of all available metadata streams. It follows
/// the ECMA-335 specification for physical metadata layout and provides access to version
/// information, stream locations, and structural metadata.
///
/// This structure is typically the first metadata component parsed when analyzing a .NET assembly,
/// as it provides the roadmap for locating all other metadata streams such as the tables stream (`#~`),
/// strings heap (`#Strings`), GUID heap (`#GUID`), blob heap (`#Blob`), and user strings heap (`#US`).
///
/// # Physical Layout
///
/// The metadata root follows this binary structure:
/// ```text
/// Offset | Size | Field           | Description
/// -------|------|-----------------|---------------------------
/// 0x00   | 4    | Signature       | Magic: 0x424A5342 ("BSJB")
/// 0x04   | 2    | MajorVersion    | Metadata format major version
/// 0x06   | 2    | MinorVersion    | Metadata format minor version  
/// 0x08   | 4    | Reserved        | Always 0
/// 0x0C   | 4    | Length          | Length of version string
/// 0x10   | N    | Version         | Version string (null-terminated)
/// ...    | 2    | Flags           | Reserved, always 0
/// ...    | 2    | StreamNumber    | Number of stream headers
/// ...    | ...  | StreamHeaders   | Array of stream headers
/// ```
///
/// # Stream Directory
///
/// The Root contains a directory of all metadata streams, each described by a [`crate::metadata::streams::StreamHeader`]
/// that specifies the stream's name, offset, and size. Common streams include:
/// - `#~` or `#-`: Compressed metadata tables stream
/// - `#Strings`: String heap for identifiers and names
/// - `#GUID`: GUID heap for type and assembly identifiers
/// - `#Blob`: Binary blob heap for signatures and complex data
/// - `#US`: User strings heap for string literals
///
/// # Examples
///
/// ## Basic Root Parsing
///
/// ```rust,no_run
/// use dotscope::metadata::root::Root;
///
/// let root = Root::read(&[
///     0x42, 0x53, 0x4A, 0x42,  // Magic signature "BSJB"
///     0x01, 0x00,              // Major version 1
///     0x00, 0x00,              // Minor version 0
///     0x00, 0x00, 0x00, 0x00,  // Reserved
///     0x0C, 0x00, 0x00, 0x00,  // Version string length
///     b'v', b'4', b'.', b'0',  // Version string "v4.0.30319"
///     b'.', b'3', b'0', b'3',
///     b'1', b'9', 0x00, 0x00,  // Null terminated + padding
///     0x00, 0x00,              // Flags
///     0x01, 0x00,              // Stream count: 1
///     0x5C, 0x00, 0x00, 0x00,  // Stream offset
///     0x08, 0x00, 0x00, 0x00,  // Stream size
///     b'#', b'~', 0x00, 0x00,  // Stream name "#~" + padding
/// ])?;
///
/// println!("Metadata version: {}", root.version);
/// println!("Found {} streams", root.stream_headers.len());
/// for stream in &root.stream_headers {
///     println!("Stream '{}' at offset 0x{:X}, size {} bytes",
///              stream.name, stream.offset, stream.size);
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// ## Stream Directory Analysis
///
/// ```rust,no_run
/// use dotscope::metadata::root::Root;
///
/// # let metadata_bytes = &[0u8; 100]; // placeholder
/// let root = Root::read(metadata_bytes)?;
///
/// // Find specific streams
/// if let Some(tables_stream) = root.stream_headers.iter()
///     .find(|s| s.name == "#~" || s.name == "#-") {
///     println!("Tables stream at offset 0x{:X}", tables_stream.offset);
/// }
///
/// if let Some(strings_stream) = root.stream_headers.iter()
///     .find(|s| s.name == "#Strings") {
///     println!("Strings heap at offset 0x{:X}", strings_stream.offset);
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// # Validation
///
/// The Root structure performs automatic validation during parsing:
/// - Verifies the magic signature matches `0x424A5342`
/// - Ensures version string length is within reasonable bounds
/// - Validates stream count and directory consistency
/// - Checks for proper null-termination of the version string
///
/// # Thread Safety
///
/// Root instances are immutable after creation and safe to share across threads.
/// All fields use thread-safe types and no internal mutability is required.
///
/// # References
///
/// - [ECMA-335 II.24.2.1: Metadata root](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf)
/// - [ECMA-335 II.24.2.2: Stream header](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Root {
    /// Magic signature identifying valid metadata: `0x424A5342` ("BSJB" in ASCII).
    ///
    /// This field must always contain the value [`CIL_HEADER_MAGIC`] for the metadata
    /// to be considered valid by the .NET runtime and analysis tools.
    pub signature: u32,

    /// Major version number of the metadata format.
    ///
    /// Typically 1 for most .NET Framework and .NET Core assemblies. This indicates
    /// the overall structure and capabilities of the metadata format.
    pub major_version: u16,

    /// Minor version number of the metadata format.
    ///
    /// Usually 1 for .NET Framework 2.0+ assemblies. Combined with `major_version`,
    /// this determines the exact metadata format specification being used.
    pub minor_version: u16,

    /// Reserved field, always 0.
    ///
    /// This field is reserved for future use and should always contain zero
    /// in valid .NET assemblies.
    pub reserved: u32,

    /// Length in bytes of the version string that follows.
    ///
    /// This includes the null terminator and any padding bytes required to
    /// align the following fields to 4-byte boundaries.
    pub length: u32,

    /// Version string identifying the .NET runtime version.
    ///
    /// Common values include:
    /// - `"v2.0.50727"` for .NET Framework 2.0/3.0/3.5
    /// - `"v4.0.30319"` for .NET Framework 4.0+
    /// - Various strings for .NET Core/.NET 5+ assemblies
    pub version: String,

    /// Reserved flags field, always 0.
    ///
    /// This field is reserved for future use and should always contain zero
    /// in current .NET assemblies.
    pub flags: u16,

    /// Number of metadata streams in the stream directory.
    ///
    /// Typical assemblies have 3-5 streams (tables, strings, GUID, blob, and optionally user strings).
    /// This count determines how many [`crate::metadata::streams::StreamHeader`] entries follow.
    pub stream_number: u16,

    /// Directory of all metadata streams in this assembly.
    ///
    /// Each entry describes a metadata stream's name, offset, and size. Common streams include:
    /// - `#~` or `#-`: Compressed metadata tables
    /// - `#Strings`: String heap for identifiers  
    /// - `#GUID`: GUID heap for type references
    /// - `#Blob`: Binary blob heap for signatures
    /// - `#US`: User strings heap for literals
    pub stream_headers: Vec<StreamHeader>,
}

impl Root {
    /// Parses a metadata root header from binary data.
    ///
    /// This method reads and validates the complete metadata root structure including the
    /// magic signature, version information, and stream directory. It performs comprehensive
    /// validation to ensure the metadata conforms to ECMA-335 specifications.
    ///
    /// # Arguments
    ///
    /// * `data` - A byte slice containing the metadata root header and stream directory.
    ///   Must start at the beginning of the metadata root structure.
    ///
    /// # Returns
    ///
    /// Returns a [`crate::Result<Root>`] containing the parsed root structure, or an error
    /// if parsing fails due to invalid data, malformed headers, or insufficient bytes.
    ///
    /// # Validation Performed
    ///
    /// This method performs extensive validation during parsing:
    /// - Verifies minimum required data length (36 bytes)
    /// - Validates magic signature matches [`CIL_HEADER_MAGIC`] (`0x424A5342`)
    /// - Checks version string length for overflow and bounds
    /// - Ensures proper null-termination of version string
    /// - Validates stream count and directory consistency
    /// - Verifies stream header alignment and bounds
    ///
    /// # Binary Format
    ///
    /// The expected binary layout is:
    /// ```text
    /// Offset | Size | Field         | Description
    /// -------|------|---------------|---------------------------
    /// 0x00   | 4    | Signature     | Magic: 0x424A5342 ("BSJB")
    /// 0x04   | 2    | MajorVersion  | Format major version
    /// 0x06   | 2    | MinorVersion  | Format minor version
    /// 0x08   | 4    | Reserved      | Always 0
    /// 0x0C   | 4    | Length        | Version string length
    /// 0x10   | N    | Version       | Null-terminated version string
    /// ...    | 2    | Flags         | Reserved, always 0
    /// ...    | 2    | StreamNumber  | Number of streams
    /// ...    | ...  | StreamHeaders | Stream directory entries
    /// ```
    ///
    /// # Examples
    ///
    /// ## Basic Parsing
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::root::Root;
    ///
    /// // Parse metadata root from assembly bytes
    /// # let metadata_bytes = &[0u8; 100]; // placeholder
    /// let root = Root::read(metadata_bytes)?;
    ///
    /// println!("Metadata version: {}", root.version);
    /// println!("Stream count: {}", root.stream_headers.len());
    ///
    /// // Validate magic signature
    /// assert_eq!(root.signature, 0x424A5342);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// ## Stream Directory Access
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::root::Root;
    ///
    /// # let metadata_bytes = &[0u8; 100]; // placeholder
    /// let root = Root::read(metadata_bytes)?;
    ///
    /// // Find the tables stream
    /// let tables_stream = root.stream_headers.iter()
    ///     .find(|stream| stream.name == "#~" || stream.name == "#-")
    ///     .expect("Tables stream not found");
    ///
    /// println!("Tables stream at offset 0x{:X}, size {} bytes",
    ///          tables_stream.offset, tables_stream.size);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - [`crate::Error::OutOfBounds`]: If the data slice is too short for the required fields
    /// - [`crate::Error::Malformed`]: If the magic signature is invalid, version string is malformed,
    ///   or stream directory is inconsistent
    /// - [`crate::Error::TypeError`]: If integer overflow occurs during parsing
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads
    /// as it performs no mutations and uses only stack-allocated temporary variables.
    pub fn read(data: &[u8]) -> Result<Root> {
        if data.len() < MIN_ROOT_HEADER_SIZE {
            return Err(out_of_bounds_error!());
        }

        let signature = read_le::<u32>(data)?;
        if signature != CIL_HEADER_MAGIC {
            return Err(malformed_error!(
                "Root: invalid signature 0x{:08X}, expected 0x{:08X} [ECMA-335 §II.24.2.1]",
                signature,
                CIL_HEADER_MAGIC
            ));
        }

        let version_string_length = read_le_at::<u32>(data, &mut { VERSION_LENGTH_OFFSET })?;
        match version_string_length.checked_add(u32::from(VERSION_STRING_OFFSET)) {
            Some(str_end) => {
                let data_len = u32::try_from(data.len()).map_err(|_| {
                    malformed_error!("Root: data length too large [ECMA-335 §II.24.2.1]")
                })?;
                if str_end > data_len {
                    return Err(out_of_bounds_error!());
                }
            }
            None => {
                return Err(malformed_error!(
                    "Root: version string length {} causes integer overflow [ECMA-335 §II.24.2.1]",
                    version_string_length
                ))
            }
        }

        let mut version_string: String = String::with_capacity(version_string_length as usize);
        for counter in 0..version_string_length {
            version_string.push(char::from(read_le_at::<u8>(
                data,
                &mut (usize::from(VERSION_STRING_OFFSET) + counter as usize),
            )?));
        }

        // Validate version string format and content
        if version_string.is_empty() {
            return Err(malformed_error!(
                "Root: version string cannot be empty [ECMA-335 §II.24.2.1]"
            ));
        }

        // Check for common malformed version strings
        if !version_string.starts_with('v') {
            return Err(malformed_error!(
                "Root: version string '{}' must start with 'v' [ECMA-335 §II.24.2.1]",
                version_string
            ));
        }

        // Validate version string contains reasonable content
        if version_string.len() > MAX_VERSION_STRING_LENGTH {
            return Err(malformed_error!(
                "Root: version string length {} exceeds reasonable limit ({}) [ECMA-335 §II.24.2.1]",
                version_string.len(),
                MAX_VERSION_STRING_LENGTH
            ));
        }

        // Stream count is located after: version_string + FLAGS_FIELD_SIZE
        let mut stream_count_offset =
            version_string.len() + usize::from(VERSION_STRING_OFFSET) + FLAGS_FIELD_SIZE;
        let stream_count = read_le_at::<u16>(data, &mut stream_count_offset)?;

        // Validate stream count: must have at least one stream, no more than MAX_STREAM_COUNT
        if stream_count == 0
            || stream_count > MAX_STREAM_COUNT
            || (stream_count as usize * MIN_STREAM_HEADER_SIZE) > data.len()
        {
            return Err(malformed_error!(
                "Root: invalid stream count {} (must be 1-{}) [ECMA-335 §II.24.2.1]",
                stream_count,
                MAX_STREAM_COUNT
            ));
        }

        let mut streams = Vec::with_capacity(stream_count as usize);
        // Stream directory starts after: version_string + FLAGS_FIELD_SIZE + STREAM_COUNT_FIELD_SIZE
        let mut stream_offset = version_string.len()
            + usize::from(VERSION_STRING_OFFSET)
            + FLAGS_FIELD_SIZE
            + STREAM_COUNT_FIELD_SIZE;
        let mut streams_seen = [false; MAX_STREAM_COUNT as usize];

        for _i in 0..stream_count {
            if stream_offset > data.len() {
                return Err(out_of_bounds_error!());
            }

            let new_stream = StreamHeader::from(&data[stream_offset..])?;
            if new_stream.offset as usize > data.len()
                || new_stream.size as usize > data.len()
                || new_stream.name.len() > MAX_STREAM_NAME_LENGTH
            {
                return Err(out_of_bounds_error!());
            }

            match u32::checked_add(new_stream.offset, new_stream.size) {
                Some(range) => {
                    if range as usize > data.len() {
                        return Err(out_of_bounds_error!());
                    }
                }
                None => {
                    return Err(malformed_error!(
                        "Root: stream '{}' offset {} + size {} causes integer overflow [ECMA-335 §II.24.2.2]",
                        new_stream.name,
                        new_stream.offset,
                        new_stream.size
                    ))
                }
            }

            let stream_index = match new_stream.name.as_str() {
                "#Strings" => 0,
                "#US" => 1,
                "#Blob" => 2,
                "#GUID" => 3,
                "#~" => 4,
                "#-" => 5,
                _ => unreachable!("StreamHeader::from() should have validated the name"),
            };

            if streams_seen[stream_index] {
                return Err(malformed_error!(
                    "Root: duplicate stream '{}' found [ECMA-335 §II.24.2.2]",
                    new_stream.name
                ));
            }
            streams_seen[stream_index] = true;

            let name_aligned = ((new_stream.name.len() + 1) + 3) & !3;
            stream_offset += STREAM_HEADER_FIXED_SIZE + name_aligned;

            streams.push(new_stream);
        }

        if streams.is_empty() {
            return Err(malformed_error!(
                "Root: no valid streams found [ECMA-335 §II.24.2.1]"
            ));
        }

        Ok(Root {
            signature,
            major_version: read_le::<u16>(&data[FIELD_OFFSET_MAJOR_VERSION..])?,
            minor_version: read_le::<u16>(&data[FIELD_OFFSET_MINOR_VERSION..])?,
            reserved: read_le::<u32>(&data[FIELD_OFFSET_RESERVED..])?,
            length: u32::try_from(version_string.len()).map_err(|_| {
                malformed_error!("Root: version string length too large [ECMA-335 §II.24.2.1]")
            })?,
            flags: read_le::<u16>(
                &data[usize::from(VERSION_STRING_OFFSET) + version_string.len()..],
            )?,
            stream_number: u16::try_from(streams.len())
                .map_err(|_| malformed_error!("Root: too many streams [ECMA-335 §II.24.2.1]"))?,
            stream_headers: streams,
            version: version_string,
        })
    }

    /// Validates that loaded streams do not overlap in memory
    ///
    /// This method should be called after all streams have been loaded and their actual
    /// positions and sizes are known. It performs comprehensive overlap detection that
    /// was deferred during initial parsing.
    ///
    /// # Arguments
    /// * `meta_root_offset` - The offset where the metadata root starts
    /// * `total_metadata_size` - The total size of the metadata section
    ///
    /// # Errors
    /// Returns an error if any streams overlap or extend beyond the metadata bounds
    pub fn validate_stream_layout(
        &self,
        meta_root_offset: usize,
        total_metadata_size: u32,
    ) -> Result<()> {
        let mut stream_ranges: Vec<(u32, u32, &str)> = Vec::new();

        // Validate stream doesn't exceed metadata bounds
        let metadata_end = meta_root_offset
            .checked_add(total_metadata_size as usize)
            .ok_or_else(|| {
                malformed_error!(
                    "Metadata size causes overflow: {} + {}",
                    meta_root_offset,
                    total_metadata_size
                )
            })?;

        // Calculate actual stream positions
        for stream in &self.stream_headers {
            let absolute_start = meta_root_offset
                .checked_add(stream.offset as usize)
                .ok_or_else(|| {
                    malformed_error!(
                        "Stream '{}' offset causes overflow: {} + {}",
                        stream.name,
                        meta_root_offset,
                        stream.offset
                    )
                })?;

            let absolute_end = absolute_start
                .checked_add(stream.size as usize)
                .ok_or_else(|| {
                    malformed_error!(
                        "Stream '{}' size causes overflow: {} + {}",
                        stream.name,
                        absolute_start,
                        stream.size
                    )
                })?;

            if absolute_end > metadata_end {
                return Err(malformed_error!(
                    "Stream '{}' extends beyond metadata bounds (end {} > metadata end {})",
                    stream.name,
                    absolute_end,
                    metadata_end
                ));
            }

            stream_ranges.push((
                u32::try_from(absolute_start).map_err(|_| {
                    malformed_error!(
                        "Stream '{}' start position {} exceeds u32 range",
                        stream.name,
                        absolute_start
                    )
                })?,
                u32::try_from(absolute_end).map_err(|_| {
                    malformed_error!(
                        "Stream '{}' end position {} exceeds u32 range",
                        stream.name,
                        absolute_end
                    )
                })?,
                &stream.name,
            ));
        }

        for (i, &(start1, end1, name1)) in stream_ranges.iter().enumerate() {
            for &(start2, end2, name2) in stream_ranges.iter().skip(i + 1) {
                if start1 < end2 && start2 < end1 {
                    return Err(malformed_error!(
                        "Stream '{}' ({}..{}) overlaps with stream '{}' ({}..{})",
                        name1,
                        start1,
                        end1,
                        name2,
                        start2,
                        end2
                    ));
                }
            }
        }

        Ok(())
    }

    /// Writes the metadata root header to a writer in ECMA-335 binary format.
    ///
    /// Serializes the complete metadata root header including signature, version info,
    /// and stream directory according to ECMA-335 Section II.24.2.1.
    ///
    /// ## Binary Format Written
    /// ```text
    /// Offset | Size | Field        | Description
    /// -------|------|--------------|----------------------------------
    /// 0x00   | 4    | Signature    | Magic: 0x424A5342 ("BSJB")
    /// 0x04   | 2    | MajorVersion | Metadata format major version
    /// 0x06   | 2    | MinorVersion | Metadata format minor version
    /// 0x08   | 4    | Reserved     | Always 0
    /// 0x0C   | 4    | Length       | Version string length (padded)
    /// 0x10   | N    | Version      | Version string + null padding
    /// ...    | 2    | Flags        | Reserved, always 0
    /// ...    | 2    | StreamNumber | Number of stream headers
    /// ...    | ...  | Streams      | Stream header directory
    /// ```
    ///
    /// # Arguments
    /// * `writer` - Any type implementing [`std::io::Write`]
    ///
    /// # Returns
    /// * `Ok(())` - Root header written successfully
    /// * `Err(Error)` - Write operation failed
    ///
    /// # Examples
    /// ```rust,no_run
    /// use dotscope::metadata::root::Root;
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// let root = Root {
    ///     signature: 0x424A5342,
    ///     major_version: 1,
    ///     minor_version: 1,
    ///     reserved: 0,
    ///     length: 12,
    ///     version: "v4.0.30319".to_string(),
    ///     flags: 0,
    ///     stream_number: 1,
    ///     stream_headers: vec![
    ///         StreamHeader { offset: 0x6C, size: 0x1000, name: "#~".to_string() },
    ///     ],
    /// };
    ///
    /// let mut buffer = Vec::new();
    /// root.write_to(&mut buffer)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the writer fails or if the version string
    /// length exceeds u32 range.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Signature (4 bytes) - "BSJB" magic
        writer.write_all(&self.signature.to_le_bytes())?;

        // Major version (2 bytes)
        writer.write_all(&self.major_version.to_le_bytes())?;

        // Minor version (2 bytes)
        writer.write_all(&self.minor_version.to_le_bytes())?;

        // Reserved (4 bytes)
        writer.write_all(&self.reserved.to_le_bytes())?;

        // Version string length (padded to 4-byte boundary)
        let version_bytes = self.version.as_bytes();
        let padded_len = (version_bytes.len() + 3) & !3;
        let padded_len_u32 = u32::try_from(padded_len).map_err(|_| {
            malformed_error!(
                "Version string padded length {} exceeds u32 range",
                padded_len
            )
        })?;
        writer.write_all(&padded_len_u32.to_le_bytes())?;

        // Version string + null padding to 4-byte boundary
        writer.write_all(version_bytes)?;
        let padding = padded_len - version_bytes.len();
        if padding > 0 {
            writer.write_all(&vec![0u8; padding])?;
        }

        // Flags (2 bytes)
        writer.write_all(&self.flags.to_le_bytes())?;

        // Stream count (2 bytes)
        writer.write_all(&self.stream_number.to_le_bytes())?;

        // Stream headers
        for stream in &self.stream_headers {
            stream.write_to(writer)?;
        }

        Ok(())
    }

    /// Returns the total serialized size of this metadata root header in bytes.
    ///
    /// The size includes the fixed header fields plus the padded version string
    /// and all stream headers with their alignment padding.
    ///
    /// # Returns
    /// The total size in bytes when written with [`write_to`](Self::write_to).
    ///
    /// # Examples
    /// ```rust
    /// use dotscope::metadata::root::Root;
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// let root = Root {
    ///     signature: 0x424A5342,
    ///     major_version: 1,
    ///     minor_version: 1,
    ///     reserved: 0,
    ///     length: 12,
    ///     version: "v4.0.30319".to_string(),
    ///     flags: 0,
    ///     stream_number: 1,
    ///     stream_headers: vec![
    ///         StreamHeader { offset: 0x6C, size: 0x1000, name: "#~".to_string() },
    ///     ],
    /// };
    ///
    /// // Fixed: 4+2+2+4+4+2+2 = 20
    /// // Version: "v4.0.30319" (10 chars) padded to 12
    /// // Stream header: 12 bytes (for "#~")
    /// // Total: 20 + 12 + 12 = 44
    /// assert_eq!(root.serialized_size(), 44);
    /// ```
    #[must_use]
    pub fn serialized_size(&self) -> usize {
        // Fixed fields: signature(4) + major(2) + minor(2) + reserved(4) + length(4) + flags(2) + stream_number(2)
        let fixed_size = 20;

        // Version string padded to 4-byte boundary
        let version_padded = (self.version.len() + 3) & !3;

        // Stream headers
        let streams_size: usize = self
            .stream_headers
            .iter()
            .map(crate::StreamHeader::serialized_size)
            .sum();

        fixed_size + version_padded + streams_size
    }
}

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

    #[test]
    fn crafted() {
        #[rustfmt::skip]
            let header_bytes = [
            0x42, 0x53, 0x4A, 0x42,
            0x00, 0x20,
            0x00, 0x30,
            0x00, 0x00, 0x00, 0x40,
            0x06, 0x00, 0x00, 0x00, // length = 6 for "v4.0.0"
            b'v', b'4', b'.', b'0', b'.', b'0',
            0x00, 0x60,
            0x01, 0x00,

            0x1, 0x00, 0x00, 0x00, // StreamHeader
            0x8, 0x00, 0x00, 0x00,
            0x23, 0x7E, 0x00,
        ];

        let parsed_header = Root::read(&header_bytes).unwrap();

        assert_eq!(parsed_header.signature, CIL_HEADER_MAGIC);
        assert_eq!(parsed_header.major_version, 0x2000);
        assert_eq!(parsed_header.minor_version, 0x3000);
        assert_eq!(parsed_header.reserved, 0x40000000);
        assert_eq!(parsed_header.length, 6);
        assert_eq!(parsed_header.version, "v4.0.0");
        assert_eq!(parsed_header.flags, 0x6000);
        assert_eq!(parsed_header.stream_number, 1);
        assert_eq!(parsed_header.stream_headers.len(), 1);
        assert_eq!(parsed_header.stream_headers[0].offset, 0x1);
        assert_eq!(parsed_header.stream_headers[0].size, 0x8);
        assert_eq!(parsed_header.stream_headers[0].name, "#~");
    }

    #[test]
    fn duplicate_stream_names_should_fail() {
        #[rustfmt::skip]
        let mut header_bytes = vec![
            0x42, 0x53, 0x4A, 0x42,  // CIL_HEADER_MAGIC
            0x00, 0x20,              // major_version
            0x00, 0x30,              // minor_version
            0x00, 0x00, 0x00, 0x40,  // reserved
            0x06, 0x00, 0x00, 0x00,  // length (version string length)
            b'v', b'4', b'.', b'0', b'.', b'0',  // version string
            0x00, 0x60,              // flags
            0x02, 0x00,              // stream_number (2 streams)

            // First StreamHeader - #~
            0x52, 0x00, 0x00, 0x00,  // offset (82 - past all headers)
            0x08, 0x00, 0x00, 0x00,  // size (8 bytes - aligned)
            0x23, 0x7E, 0x00, 0x00,  // "#~\0" + padding

            // Second StreamHeader - duplicate #~
            0x5A, 0x00, 0x00, 0x00,  // offset (90 - after first stream)
            0x08, 0x00, 0x00, 0x00,  // size (8 bytes - aligned)
            0x23, 0x7E, 0x00, 0x00,  // "#~\0" + padding (duplicate)
        ];

        // Add enough padding to reach offset 82 and then the stream data
        header_bytes.resize(98, 0x00);

        let result = Root::read(&header_bytes);
        let err = result.expect_err("Expected error for duplicate stream names");
        let error_string = err.to_string();
        assert!(
            error_string.contains("duplicate stream") && error_string.contains("#~"),
            "Expected error about duplicate stream '#~', got: {}",
            error_string
        );
    }

    #[test]
    fn test_write_to_basic() {
        let root = Root {
            signature: CIL_HEADER_MAGIC,
            major_version: 1,
            minor_version: 1,
            reserved: 0,
            length: 12, // Will be recalculated during write
            version: "v4.0.30319".to_string(),
            flags: 0,
            stream_number: 1,
            stream_headers: vec![StreamHeader {
                offset: 0x6C,
                size: 0x1000,
                name: "#~".to_string(),
            }],
        };

        let mut buffer = Vec::new();
        root.write_to(&mut buffer).unwrap();

        // Verify signature "BSJB"
        assert_eq!(&buffer[0..4], &[0x42, 0x53, 0x4A, 0x42]);
        // Verify major version
        assert_eq!(&buffer[4..6], &[0x01, 0x00]);
        // Verify minor version
        assert_eq!(&buffer[6..8], &[0x01, 0x00]);
        // Verify reserved
        assert_eq!(&buffer[8..12], &[0x00, 0x00, 0x00, 0x00]);
        // Verify version string length (padded to 12)
        assert_eq!(&buffer[12..16], &[0x0C, 0x00, 0x00, 0x00]);
        // Verify version string starts with "v4.0"
        assert_eq!(&buffer[16..20], b"v4.0");
    }

    #[test]
    fn test_serialized_size() {
        let root = Root {
            signature: CIL_HEADER_MAGIC,
            major_version: 1,
            minor_version: 1,
            reserved: 0,
            length: 12,
            version: "v4.0.30319".to_string(), // 10 chars, padded to 12
            flags: 0,
            stream_number: 1,
            stream_headers: vec![StreamHeader {
                offset: 0x6C,
                size: 0x1000,
                name: "#~".to_string(), // "#~" + null (3) padded to 4, + 8 fixed = 12
            }],
        };

        // Fixed: 20 bytes
        // Version: 12 bytes (10 chars padded to 12)
        // Stream header: 12 bytes
        // Total: 44 bytes
        assert_eq!(root.serialized_size(), 44);
    }

    #[test]
    fn test_serialized_size_multiple_streams() {
        let root = Root {
            signature: CIL_HEADER_MAGIC,
            major_version: 1,
            minor_version: 1,
            reserved: 0,
            length: 12,
            version: "v4.0.30319".to_string(),
            flags: 0,
            stream_number: 3,
            stream_headers: vec![
                StreamHeader {
                    offset: 0x6C,
                    size: 0x1000,
                    name: "#~".to_string(),
                }, // 12 bytes
                StreamHeader {
                    offset: 0x106C,
                    size: 0x500,
                    name: "#Strings".to_string(),
                }, // 20 bytes
                StreamHeader {
                    offset: 0x156C,
                    size: 0x100,
                    name: "#Blob".to_string(),
                }, // 16 bytes
            ],
        };

        // Fixed: 20 bytes
        // Version: 12 bytes
        // Stream headers: 12 + 20 + 16 = 48 bytes
        // Total: 80 bytes
        assert_eq!(root.serialized_size(), 80);
    }
}