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
//! Metadata heap validation for .NET assembly heap integrity and format compliance.
//!
//! This validator ensures the structural integrity of all metadata heaps, including
//! proper formatting, bounds checking, and encoding validation. It operates on raw
//! heap data to validate the foundational requirements before higher-level content
//! validation can proceed. This validator runs with priority 180 in the raw validation
//! stage, providing essential heap integrity guarantees.
//!
//! # Architecture
//!
//! The heap validation system implements comprehensive heap validation strategies in sequential order:
//! 1. **String Heap Validation** - Ensures UTF-8 encoding and null-termination compliance for #Strings stream
//! 2. **Blob Heap Validation** - Validates binary data integrity and size encoding for #Blob stream
//! 3. **GUID Heap Validation** - Verifies GUID format and alignment requirements for #GUID stream
//! 4. **UserString Heap Validation** - Ensures UTF-16 encoding and proper length prefixes for #US stream
//!
//! The implementation validates each heap type according to ECMA-335 specifications,
//! ensuring proper format compliance and data integrity across all metadata heaps.
//! All heap validation performs bounds checking and alignment verification.
//!
//! # Key Components
//!
//! - [`crate::metadata::validation::validators::raw::structure::heap::RawHeapValidator`] - Main validator implementation providing comprehensive heap validation
//! - [`crate::metadata::validation::validators::raw::structure::heap::RawHeapValidator::validate_string_heap`] - String heap format validation with UTF-8 compliance checking
//! - [`crate::metadata::validation::validators::raw::structure::heap::RawHeapValidator::validate_blob_heap`] - Blob heap integrity validation with size encoding verification
//! - [`crate::metadata::validation::validators::raw::structure::heap::RawHeapValidator::validate_guid_heap`] - GUID heap format validation with 16-byte alignment checking
//! - [`crate::metadata::validation::validators::raw::structure::heap::RawHeapValidator::validate_userstring_heap`] - UserString heap encoding validation with UTF-16 compliance
//!
//! # Usage Examples
//!
//! ```rust,no_run
//! use dotscope::metadata::validation::{RawHeapValidator, RawValidator, RawValidationContext};
//!
//! # fn get_context() -> RawValidationContext<'static> { unimplemented!() }
//! let context = get_context();
//! let validator = RawHeapValidator::new();
//!
//! // Check if validation should run based on configuration
//! if validator.should_run(&context) {
//!     validator.validate_raw(&context)?;
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Error Handling
//!
//! This validator returns [`crate::Error::ValidationRawFailed`] for:
//! - Invalid UTF-8 encoding in string heaps (#Strings stream violations)
//! - Malformed blob size encoding or data corruption (#Blob stream violations)
//! - Incorrect GUID alignment or invalid format (#GUID stream violations)
//! - Invalid UTF-16 encoding in user string heaps (#US stream violations)
//! - Heap data extending beyond stream boundaries (size/offset limit violations)
//! - Non-aligned heap sizes violating ECMA-335 4-byte alignment requirements
//! - Stream sizes exceeding maximum allowed values (0x7FFFFFFF)
//!
//! # Thread Safety
//!
//! All validation operations are read-only and thread-safe. The validator implements [`Send`] + [`Sync`]
//! and can be used concurrently across multiple threads without synchronization as it operates on
//! immutable heap structures.
//!
//! # Integration
//!
//! This validator integrates with:
//! - raw structure validators - Part of the foundational structural validation stage
//! - [`crate::metadata::validation::engine::ValidationEngine`] - Orchestrates validator execution with fail-fast behavior
//! - [`crate::metadata::validation::traits::RawValidator`] - Implements the raw validation interface
//! - [`crate::metadata::cilassemblyview::CilAssemblyView`] - Source of metadata heaps and stream information
//! - [`crate::metadata::validation::context::RawValidationContext`] - Provides validation execution context
//! - [`crate::metadata::validation::config::ValidationConfig`] - Controls validation execution via enable_structural_validation flag
//!
//! # References
//!
//! - [ECMA-335 II.24.2.3](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - String heap specification
//! - [ECMA-335 II.24.2.4](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Blob heap specification
//! - [ECMA-335 II.24.2.5](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - GUID heap specification
//! - [ECMA-335 II.24.2.6](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - UserString heap specification

use crate::{
    metadata::{
        cilassemblyview::CilAssemblyView,
        validation::{
            context::{RawValidationContext, ValidationContext},
            traits::RawValidator,
        },
    },
    Result,
};

/// Foundation validator for metadata heap structure and encoding compliance.
///
/// Ensures the structural integrity and format compliance of all metadata heaps
/// in a .NET assembly, validating proper encoding, bounds checking, and format
/// requirements. This validator operates at the lowest level of heap validation,
/// providing essential guarantees before higher-level content validation can proceed.
///
/// The validator implements comprehensive coverage of all heap types according to
/// ECMA-335 specifications, ensuring proper UTF-8/UTF-16 encoding, data integrity,
/// and structural compliance across all metadata heap formats.
///
/// # Thread Safety
///
/// This validator is [`Send`] and [`Sync`] as all validation operations are read-only
/// and operate on immutable heap structures.
pub struct RawHeapValidator;

impl RawHeapValidator {
    /// Creates a new metadata heap validator.
    ///
    /// Initializes a validator instance that can be used to validate metadata
    /// heap structures across multiple assemblies. The validator is stateless
    /// and can be reused safely across multiple validation operations.
    ///
    /// # Returns
    ///
    /// A new [`RawHeapValidator`] instance ready for validation operations.
    ///
    /// # Thread Safety
    ///
    /// The returned validator is thread-safe and can be used concurrently.
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Validates the string heap for UTF-8 encoding compliance and proper formatting.
    ///
    /// Ensures that the string heap (#Strings) conforms to ECMA-335 requirements,
    /// including proper null-termination, valid UTF-8 encoding, and correct heap
    /// structure. Validates size and alignment requirements for the heap.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing heap data via [`crate::metadata::cilassemblyview::CilAssemblyView`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - String heap is valid and properly formatted
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - String heap violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - String heap size exceeds maximum allowed value (0x7FFFFFFF)
    /// - String heap size is not 4-byte aligned as required by ECMA-335
    /// - String heap offset exceeds maximum allowed value
    /// - String entries contain invalid UTF-8 sequences
    /// - String entries are not properly null-terminated
    fn validate_string_heap(assembly_view: &CilAssemblyView) -> Result<()> {
        let streams = assembly_view.streams();

        let strings_stream = streams.iter().find(|s| s.name == "#Strings");
        if let Some(stream) = strings_stream {
            if stream.size > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "String heap (#Strings) size {} exceeds maximum allowed size",
                    stream.size
                ));
            }

            if stream.size % 4 != 0 {
                return Err(malformed_error!(
                    "String heap (#Strings) size {} is not 4-byte aligned as required by ECMA-335",
                    stream.size
                ));
            }

            if stream.offset > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "String heap (#Strings) offset {} exceeds maximum allowed offset",
                    stream.offset
                ));
            }
        }

        // Validate string heap content
        Self::validate_string_heap_content(assembly_view)?;

        Ok(())
    }

    /// Validates the actual content of the string heap for UTF-8 compliance and null-termination.
    ///
    /// Performs deep content validation of string heap entries according to ECMA-335 requirements.
    /// Each string must be valid UTF-8 and properly null-terminated.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing string heap data
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All string entries are valid UTF-8 and properly formatted
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - Invalid string content found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - String contains invalid UTF-8 byte sequences
    /// - String is not properly null-terminated (ECMA-335 requirement)
    /// - String heap iteration fails due to corruption
    fn validate_string_heap_content(assembly_view: &CilAssemblyView) -> Result<()> {
        if let Some(strings) = assembly_view.strings() {
            for (offset, string_data) in strings.iter() {
                if std::str::from_utf8(string_data.as_bytes()).is_err() {
                    return Err(malformed_error!(
                        "String heap contains invalid UTF-8 sequence at offset {}",
                        offset
                    ));
                }
            }
        }

        Ok(())
    }

    /// Validates the blob heap for data integrity and proper size encoding.
    ///
    /// Ensures that the blob heap (#Blob) conforms to ECMA-335 requirements,
    /// including proper size encoding using compressed integers and valid blob
    /// boundaries. Validates size and alignment requirements for the heap.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing heap data via [`crate::metadata::cilassemblyview::CilAssemblyView`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Blob heap is valid and properly formatted
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - Blob heap violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - Blob heap size exceeds maximum allowed value (0x7FFFFFFF)
    /// - Blob heap size is not 4-byte aligned as required by ECMA-335
    /// - Blob heap offset exceeds maximum allowed value
    /// - Blob entries have invalid size encoding or data corruption
    fn validate_blob_heap(assembly_view: &CilAssemblyView) -> Result<()> {
        let streams = assembly_view.streams();

        let blob_stream = streams.iter().find(|s| s.name == "#Blob");

        if let Some(stream) = blob_stream {
            if stream.size > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "Blob heap (#Blob) size {} exceeds maximum allowed size",
                    stream.size
                ));
            }

            if stream.size % 4 != 0 {
                return Err(malformed_error!(
                    "Blob heap (#Blob) size {} is not 4-byte aligned as required by ECMA-335",
                    stream.size
                ));
            }

            if stream.offset > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "Blob heap (#Blob) offset {} exceeds maximum allowed offset",
                    stream.offset
                ));
            }
        }

        Self::validate_blob_heap_content(assembly_view)?;

        Ok(())
    }

    /// Validates the actual content of the blob heap for proper size encoding and data integrity.
    ///
    /// Performs deep content validation of blob heap entries according to ECMA-335 requirements.
    /// Each blob must have valid compressed integer size prefixes and consistent data length.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing blob heap data
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All blob entries have valid size encoding and data integrity
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - Invalid blob content found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - Blob has invalid compressed integer size prefix
    /// - Blob data length doesn't match encoded size
    /// - Blob heap iteration fails due to corruption
    fn validate_blob_heap_content(assembly_view: &CilAssemblyView) -> Result<()> {
        if let Some(blobs) = assembly_view.blobs() {
            for (offset, blob_data) in blobs.iter() {
                if blob_data.len() > 0x1FFF_FFFF {
                    return Err(malformed_error!(
                        "Blob at offset {} has excessive size {} bytes (max: {})",
                        offset,
                        blob_data.len(),
                        0x1FFF_FFFF
                    ));
                }

                // Note: More sophisticated blob content validation could include:
                // - Validating compressed integer encoding in the raw blob stream
                // - Checking that size prefixes match actual data lengths
                // - Validating specific blob content formats (signatures, etc.)
                // These would require access to the raw blob stream data
            }
        }

        Ok(())
    }

    /// Validates the GUID heap for proper format and alignment.
    ///
    /// Ensures that the GUID heap (#GUID) conforms to ECMA-335 requirements,
    /// including proper 16-byte GUID alignment and valid heap structure.
    /// Validates that the heap contains only complete GUID entries.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing heap data via [`crate::metadata::cilassemblyview::CilAssemblyView`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - GUID heap is valid and properly formatted
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - GUID heap violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - GUID heap size exceeds maximum allowed value (0x7FFFFFFF)
    /// - GUID heap size is not a multiple of 16 bytes (GUID entry size)
    /// - GUID heap size is not 4-byte aligned as required by ECMA-335
    /// - GUID heap offset exceeds maximum allowed value
    /// - GUID entries are malformed or contain invalid data
    fn validate_guid_heap(assembly_view: &CilAssemblyView) -> Result<()> {
        let streams = assembly_view.streams();
        let guid_stream = streams.iter().find(|s| s.name == "#GUID");

        if let Some(stream) = guid_stream {
            if stream.size > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "GUID heap (#GUID) size {} exceeds maximum allowed size",
                    stream.size
                ));
            }

            if stream.size % 16 != 0 {
                return Err(malformed_error!(
                    "GUID heap (#GUID) size {} is not a multiple of 16 bytes (GUID size)",
                    stream.size
                ));
            }

            if stream.size % 4 != 0 {
                return Err(malformed_error!(
                    "GUID heap (#GUID) size {} is not 4-byte aligned as required by ECMA-335",
                    stream.size
                ));
            }

            if stream.offset > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "GUID heap (#GUID) offset {} exceeds maximum allowed offset",
                    stream.offset
                ));
            }
        }

        Self::validate_guid_heap_content(assembly_view)?;

        Ok(())
    }

    /// Validates the actual content of the GUID heap for proper GUID format and data integrity.
    ///
    /// Performs deep content validation of GUID heap entries according to ECMA-335 requirements.
    /// Each GUID must be exactly 16 bytes and accessible through the heap interface.
    /// Validates GUID heap accessibility, iteration capability, and basic format compliance.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing GUID heap data
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All GUID entries are properly formatted and accessible
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - Invalid GUID content found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - GUID heap iteration fails due to corruption
    /// - GUID entries are inaccessible or malformed
    /// - GUID heap contains inconsistent data
    /// - Individual GUID access fails unexpectedly
    fn validate_guid_heap_content(assembly_view: &CilAssemblyView) -> Result<()> {
        if let Some(guids) = assembly_view.guids() {
            let mut guid_count = 0;

            // Validate accessibility through iteration
            // Note: The GUID iterator returns (1-based index, GUID), not byte offsets
            for (one_based_index, guid_data) in guids.iter() {
                guid_count += 1;

                // Verify GUID data is properly accessible
                let guid_bytes = guid_data.to_bytes();

                // GUID format validation: ensure it's exactly 16 bytes
                if guid_bytes.len() != 16 {
                    return Err(malformed_error!(
                        "GUID at index {} has invalid length {} (expected 16 bytes)",
                        one_based_index,
                        guid_bytes.len()
                    ));
                }

                // Verify 1-based indexing access returns the same GUID
                match guids.get(one_based_index) {
                    Ok(indexed_guid) => {
                        let indexed_bytes = indexed_guid.to_bytes();
                        if indexed_bytes != guid_bytes {
                            return Err(malformed_error!(
                                "GUID heap consistency error: iterator and indexed access return different data for index {}",
                                one_based_index
                            ));
                        }
                    }
                    Err(_) => {
                        return Err(malformed_error!(
                            "GUID heap access error: cannot access GUID at 1-based index {}",
                            one_based_index
                        ));
                    }
                }

                // Prevent excessive iteration in case of heap corruption
                if guid_count > 65536 {
                    return Err(malformed_error!(
                        "GUID heap contains excessive number of entries (>65536), possible corruption"
                    ));
                }
            }

            // Verify count consistency with heap size
            let streams = assembly_view.streams();
            if let Some(guid_stream) = streams.iter().find(|s| s.name == "#GUID") {
                let expected_count = (guid_stream.size / 16) as usize;
                if guid_count != expected_count {
                    return Err(malformed_error!(
                        "GUID heap count mismatch: found {} GUIDs but stream size {} indicates {} GUIDs",
                        guid_count,
                        guid_stream.size,
                        expected_count
                    ));
                }
            }
        }

        Ok(())
    }

    /// Validates the user string heap for UTF-16 encoding compliance and proper length prefixes.
    ///
    /// Ensures that the user string heap (#US) conforms to ECMA-335 requirements,
    /// including proper length prefixing, valid UTF-16 encoding, and correct heap
    /// structure. Validates size and alignment requirements for the heap.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing heap data via [`crate::metadata::cilassemblyview::CilAssemblyView`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - UserString heap is valid and properly formatted
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - UserString heap violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - UserString heap size exceeds maximum allowed value (0x7FFFFFFF)
    /// - UserString heap size is not 4-byte aligned as required by ECMA-335
    /// - UserString heap offset exceeds maximum allowed value
    /// - UserString entries have invalid UTF-16 encoding or length prefixes
    fn validate_userstring_heap(assembly_view: &CilAssemblyView) -> Result<()> {
        let streams = assembly_view.streams();

        let us_stream = streams.iter().find(|s| s.name == "#US");

        if let Some(stream) = us_stream {
            if stream.size > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "UserString heap (#US) size {} exceeds maximum allowed size",
                    stream.size
                ));
            }

            if stream.size % 4 != 0 {
                return Err(malformed_error!(
                    "UserString heap (#US) size {} is not 4-byte aligned as required by ECMA-335",
                    stream.size
                ));
            }

            if stream.offset > 0x7FFF_FFFF {
                return Err(malformed_error!(
                    "UserString heap (#US) offset {} exceeds maximum allowed offset",
                    stream.offset
                ));
            }
        }

        Self::validate_userstring_heap_content(assembly_view)?;

        Ok(())
    }

    /// Validates the actual content of the user string heap for UTF-16 compliance and length prefixes.
    ///
    /// Performs deep content validation of user string heap entries according to ECMA-335 requirements.
    /// Each user string must have valid UTF-16 encoding and proper length prefixing.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Assembly metadata view containing user string heap data
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All user string entries are valid UTF-16 and properly formatted
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - Invalid user string content found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] if:
    /// - User string contains invalid UTF-16 encoding
    /// - User string length prefix is malformed
    /// - User string heap iteration fails due to corruption
    fn validate_userstring_heap_content(assembly_view: &CilAssemblyView) -> Result<()> {
        if let Some(userstrings) = assembly_view.userstrings() {
            for (offset, userstring_data) in userstrings.iter().take(1000) {
                let utf16_chars = userstring_data.as_slice();
                if utf16_chars.len() > 0x1FFF_FFFF {
                    return Err(malformed_error!(
                        "UserString at offset {} has excessive length {} characters (max: {})",
                        offset,
                        utf16_chars.len(),
                        0x1FFF_FFFF
                    ));
                }

                if String::from_utf16(utf16_chars).is_err() {
                    return Err(malformed_error!(
                        "UserString heap contains invalid UTF-16 sequence at offset {}",
                        offset
                    ));
                }
            }
        }

        Ok(())
    }
}

impl RawValidator for RawHeapValidator {
    /// Validates the structural integrity and format compliance of all metadata heaps.
    ///
    /// Performs comprehensive validation of heap structures, including:
    /// 1. String heap UTF-8 encoding and null-termination validation
    /// 2. Blob heap data integrity and size encoding validation
    /// 3. GUID heap format and alignment validation
    /// 4. UserString heap UTF-16 encoding and length prefix validation
    ///
    /// This method provides foundational guarantees about metadata heap integrity
    /// that higher-level validators can rely upon during content validation.
    ///
    /// # Arguments
    ///
    /// * `context` - Raw validation context containing assembly view and configuration
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All heap structures are valid and meet ECMA-335 requirements
    /// * `Err(`[`crate::Error::ValidationRawFailed`]`)` - Heap structure violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationRawFailed`] for:
    /// - Invalid UTF-8 encoding in string heaps
    /// - Malformed blob size encoding or corrupted data
    /// - Incorrect GUID alignment or invalid format
    /// - Invalid UTF-16 encoding in user string heaps
    /// - Heap data extending beyond stream boundaries
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and performs only read-only operations on metadata.
    fn validate_raw(&self, context: &RawValidationContext) -> Result<()> {
        let assembly_view = context.assembly_view();

        Self::validate_string_heap(assembly_view)?;
        Self::validate_blob_heap(assembly_view)?;
        Self::validate_guid_heap(assembly_view)?;
        Self::validate_userstring_heap(assembly_view)?;

        Ok(())
    }

    fn name(&self) -> &'static str {
        "RawHeapValidator"
    }

    fn priority(&self) -> u32 {
        180
    }

    fn should_run(&self, context: &RawValidationContext) -> bool {
        context.config().enable_structural_validation
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        metadata::validation::ValidationConfig,
        test::{
            factories::validation::raw_structure_heap::*, get_testfile_wb, validator_test,
            TestAssembly,
        },
        Error, Result,
    };

    #[test]
    fn test_raw_heap_validator() -> Result<()> {
        let validator = RawHeapValidator::new();
        let config = ValidationConfig {
            enable_structural_validation: true,
            ..Default::default()
        };

        validator_test(
            raw_heap_validator_file_factory,
            "RawHeapValidator",
            "Malformed",
            config,
            |context| validator.validate_raw(context),
        )
    }

    #[test]
    fn test_raw_heap_validator_configuration() -> Result<()> {
        let validator = RawHeapValidator::new();

        fn clean_only_factory() -> Result<Vec<TestAssembly>> {
            let Some(clean_testfile) = get_testfile_wb() else {
                return Err(Error::Other("WindowsBase.dll not available".to_string()));
            };
            Ok(vec![TestAssembly::new(&clean_testfile, true)])
        }

        // Test disabled configuration
        let result_disabled = validator_test(
            clean_only_factory,
            "RawHeapValidator",
            "Malformed",
            ValidationConfig {
                enable_structural_validation: false,
                ..Default::default()
            },
            |context| {
                if validator.should_run(context) {
                    validator.validate_raw(context)
                } else {
                    Ok(())
                }
            },
        );

        assert!(
            result_disabled.is_ok(),
            "Configuration test failed: validator should not run when disabled"
        );

        // Test enabled configuration
        let result_enabled = validator_test(
            clean_only_factory,
            "RawHeapValidator",
            "Malformed",
            ValidationConfig {
                enable_structural_validation: true,
                ..Default::default()
            },
            |context| validator.validate_raw(context),
        );

        assert!(
            result_enabled.is_ok(),
            "Configuration test failed: validator should run when enabled"
        );
        Ok(())
    }

    #[test]
    fn test_raw_heap_validator_metadata() {
        let validator = RawHeapValidator::new();

        assert_eq!(validator.name(), "RawHeapValidator");
        assert_eq!(validator.priority(), 180);

        let _config_enabled = ValidationConfig {
            enable_structural_validation: true,
            ..Default::default()
        };
        let _config_disabled = ValidationConfig {
            enable_structural_validation: false,
            ..Default::default()
        };
    }
}