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
//! Owned assembly validator for assembly-level validation.
//!
//! This validator provides comprehensive validation of assembly-level metadata within the context
//! of fully resolved .NET metadata. It operates on resolved assembly structures to validate
//! cross-assembly references, version compatibility, and assembly integrity constraints.
//! This validator ensures that assemblies are properly formed and don't violate ECMA-335
//! assembly model requirements. This validator runs with priority 110 in the owned validation stage.
//!
//! # Architecture
//!
//! The assembly validation system implements comprehensive assembly-level validation in sequential order:
//! 1. **Assembly Metadata Consistency Validation** - Ensures assembly-level metadata is properly formed and complete
//! 2. **Cross-Assembly Reference Validation** - Validates external assembly references and resolution
//! 3. **Assembly Version Compatibility Validation** - Ensures version dependencies are compatible and consistent
//! 4. **Module File Consistency Validation** - Validates modules and files are properly registered within assemblies
//!
//! The implementation validates assembly constraints according to ECMA-335 specifications,
//! ensuring proper assembly formation and dependency management.
//! All validation includes reference checking and version compatibility verification.
//!
//! # Key Components
//!
//! - [`crate::metadata::validation::validators::owned::system::assembly::OwnedAssemblyValidator`] - Main validator implementation providing comprehensive assembly validation
//! - [`crate::metadata::validation::validators::owned::system::assembly::OwnedAssemblyValidator::validate_assembly_metadata_consistency`] - Assembly metadata consistency and completeness validation
//! - [`crate::metadata::validation::validators::owned::system::assembly::OwnedAssemblyValidator::validate_cross_assembly_references`] - Cross-assembly reference validation and resolution checking
//! - [`crate::metadata::validation::validators::owned::system::assembly::OwnedAssemblyValidator::validate_assembly_version_compatibility`] - Assembly version compatibility and dependency validation
//! - [`crate::metadata::validation::validators::owned::system::assembly::OwnedAssemblyValidator::validate_module_file_consistency`] - Module and file consistency validation within assemblies
//!
//! # Usage Examples
//!
//! ```rust,no_run
//! use dotscope::metadata::validation::{OwnedAssemblyValidator, OwnedValidator, OwnedValidationContext};
//!
//! # fn get_context() -> OwnedValidationContext<'static> { unimplemented!() }
//! let context = get_context();
//! let validator = OwnedAssemblyValidator::new();
//!
//! // Check if validation should run based on configuration
//! if validator.should_run(&context) {
//!     validator.validate_owned(&context)?;
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Error Handling
//!
//! This validator returns [`crate::Error::ValidationOwnedFailed`] for:
//! - Assembly metadata consistency violations (empty names, invalid formats, excessive lengths)
//! - Cross-assembly reference failures (unresolved references, invalid public keys, malformed identities)
//! - Version compatibility issues (suspicious version numbers, all-zero versions, excessive values)
//! - Module file consistency violations (invalid modules, corrupted PE files, suspicious sizes)
//! - Strong name validation failures (invalid public keys, zero tokens, malformed signatures)
//! - Custom attribute violations (excessive arguments, malformed attribute data)
//!
//! # 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 resolved metadata structures.
//!
//! # Integration
//!
//! This validator integrates with:
//! - owned system validators - Part of the owned system validation stage
//! - [`crate::metadata::validation::engine::ValidationEngine`] - Orchestrates validator execution
//! - [`crate::metadata::validation::traits::OwnedValidator`] - Implements the owned validation interface
//! - [`crate::metadata::cilobject::CilObject`] - Source of resolved assembly structures
//! - [`crate::metadata::validation::context::OwnedValidationContext`] - Provides validation execution context
//! - [`crate::metadata::validation::config::ValidationConfig`] - Controls validation execution via enable_semantic_validation flag
//!
//! # References
//!
//! - [ECMA-335 II.6.2](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Assemblies and modules
//! - [ECMA-335 II.22.2](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - AssemblyRef table
//! - [ECMA-335 II.22.20](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Assembly table
//! - [ECMA-335 II.22.14](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - File table
//! - [ECMA-335 I.6.3](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Application domains and assemblies

use crate::{
    metadata::{
        identity::Identity,
        validation::{
            context::{OwnedValidationContext, ValidationContext},
            traits::OwnedValidator,
        },
    },
    Error, Result,
};
use std::sync::Arc;

/// Foundation validator for assembly-level metadata, references, and integrity constraints.
///
/// Ensures the structural integrity and consistency of assembly-level metadata in resolved .NET metadata,
/// validating assembly metadata completeness, cross-assembly reference resolution, version compatibility,
/// and module file consistency. This validator operates on resolved assembly structures to provide
/// essential guarantees about assembly integrity and ECMA-335 compliance.
///
/// The validator implements comprehensive coverage of assembly validation according to
/// ECMA-335 specifications, ensuring proper assembly formation and dependency management
/// in the resolved metadata object model.
///
/// # Thread Safety
///
/// This validator is [`Send`] and [`Sync`] as all validation operations are read-only
/// and operate on immutable resolved metadata structures.
pub struct OwnedAssemblyValidator;

impl OwnedAssemblyValidator {
    /// Creates a new assembly validator instance.
    ///
    /// Initializes a validator instance that can be used to validate assembly-level metadata
    /// across multiple assemblies. The validator is stateless and can be reused safely
    /// across multiple validation operations.
    ///
    /// # Returns
    ///
    /// A new [`OwnedAssemblyValidator`] 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
    }
}

impl OwnedAssemblyValidator {
    /// Validates assembly metadata consistency and completeness.
    ///
    /// Ensures that assembly-level metadata is properly formed and contains
    /// all required information according to ECMA-335 specifications.
    /// Validates assembly names, versions, cultures, public keys, and custom attributes.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved assembly structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All assembly metadata is consistent and complete
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Metadata consistency violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Assembly has empty or invalid name format
    /// - Assembly version components are invalid or excessive
    /// - Culture format is malformed
    /// - Public key has invalid size or suspicious patterns
    /// - Custom attributes have excessive argument counts
    fn validate_assembly_metadata_consistency(
        &self,
        context: &OwnedValidationContext,
    ) -> Result<()> {
        let assembly_info = context.object().assembly();

        if let Some(assembly) = assembly_info {
            // Validate basic assembly properties
            if assembly.name.is_empty() {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: "Assembly has empty name".to_string(),
                });
            }

            // Validate assembly name format
            if !Self::is_valid_assembly_name(&assembly.name) {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!("Assembly has invalid name format: '{}'", assembly.name),
                });
            }

            // Validate version information
            self.validate_assembly_version(assembly)?;

            // Validate culture information
            if let Some(culture) = &assembly.culture {
                if !Self::is_valid_culture_format(culture) {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!("Assembly has invalid culture format: '{culture}'"),
                    });
                }
            }

            // Validate public key information
            if let Some(public_key) = &assembly.public_key {
                self.validate_assembly_public_key(public_key)?;
            }

            // Validate custom attributes
            self.validate_assembly_custom_attributes(assembly)?;
        }

        Ok(())
    }

    /// Validates assembly name format.
    fn is_valid_assembly_name(name: &str) -> bool {
        // Assembly names must be valid identifiers
        if name.is_empty() || name.len() > 260 {
            return false;
        }

        // Check for invalid characters
        let invalid_chars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
        if name.chars().any(|c| invalid_chars.contains(&c)) {
            return false;
        }

        // Must not start with whitespace or dot
        if name.starts_with(' ') || name.starts_with('.') {
            return false;
        }

        true
    }

    /// Validates assembly version information.
    fn validate_assembly_version(
        &self,
        assembly: &Arc<crate::metadata::tables::Assembly>,
    ) -> Result<()> {
        // Version components should be reasonable
        if assembly.major_version > 65535
            || assembly.minor_version > 65535
            || assembly.build_number > 65535
            || assembly.revision_number > 65535
        {
            return Err(Error::ValidationOwnedFailed {
                validator: self.name().to_string(),
                message: format!(
                    "Assembly '{}' has invalid version components: {}.{}.{}.{}",
                    assembly.name,
                    assembly.major_version,
                    assembly.minor_version,
                    assembly.build_number,
                    assembly.revision_number
                ),
            });
        }

        Ok(())
    }

    /// Validates culture format.
    fn is_valid_culture_format(culture: &str) -> bool {
        if culture.is_empty() || culture == "neutral" {
            return true;
        }

        // Standard culture format validation
        let parts: Vec<&str> = culture.split('-').collect();
        match parts.len() {
            1 => {
                // Language only (e.g., "en", "fr")
                parts[0].len() == 2 && parts[0].chars().all(|c| c.is_ascii_lowercase())
            }
            2 => {
                // Language-Country (e.g., "en-US", "fr-FR")
                parts[0].len() == 2
                    && parts[0].chars().all(|c| c.is_ascii_lowercase())
                    && parts[1].len() == 2
                    && parts[1].chars().all(|c| c.is_ascii_uppercase())
            }
            _ => false,
        }
    }

    /// Validates assembly public key format.
    fn validate_assembly_public_key(&self, public_key: &[u8]) -> Result<()> {
        // Public key should be reasonable size
        if public_key.is_empty() {
            return Ok(()); // Empty public key is valid (no strong name)
        }

        // Valid public key sizes per ECMA-335:
        // - 16 bytes: ECMA keys for framework assemblies
        // - 160+ bytes: Full RSA public keys for strong-named assemblies
        if public_key.len() != 16 && (public_key.len() < 160 || public_key.len() > 2048) {
            return Err(Error::ValidationOwnedFailed {
                validator: self.name().to_string(),
                message: format!(
                    "Assembly public key has invalid size: {} bytes. Expected 16 bytes (ECMA key) or 160-2048 bytes (RSA key)",
                    public_key.len()
                ),

            });
        }

        // Check for suspicious patterns (all zeros, all ones, etc.)
        if public_key.iter().all(|&b| b == 0) {
            return Err(Error::ValidationOwnedFailed {
                validator: self.name().to_string(),
                message: "Assembly public key consists entirely of zero bytes".to_string(),
            });
        }

        if public_key.iter().all(|&b| b == 0xFF) {
            return Err(Error::ValidationOwnedFailed {
                validator: self.name().to_string(),
                message: "Assembly public key consists entirely of 0xFF bytes".to_string(),
            });
        }

        Ok(())
    }

    /// Validates assembly custom attributes.
    fn validate_assembly_custom_attributes(
        &self,
        assembly: &Arc<crate::metadata::tables::Assembly>,
    ) -> Result<()> {
        for (_, custom_attr) in assembly.custom_attributes.iter() {
            // Check for reasonable number of arguments
            if custom_attr.fixed_args.len() > 20 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly '{}' has custom attribute with excessive fixed arguments ({})",
                        assembly.name,
                        custom_attr.fixed_args.len()
                    ),
                });
            }

            if custom_attr.named_args.len() > 50 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly '{}' has custom attribute with excessive named arguments ({})",
                        assembly.name,
                        custom_attr.named_args.len()
                    ),
                });
            }
        }

        Ok(())
    }

    /// Validates cross-assembly reference validation and resolution.
    ///
    /// Ensures that all assembly references can be resolved and that
    /// cross-assembly dependencies are properly formed and accessible.
    /// Validates assembly references, type references, and member references.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved assembly structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All cross-assembly references are valid and resolvable
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Cross-assembly reference violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Assembly references have empty names or excessive lengths
    /// - Culture formats are invalid in references
    /// - Public key tokens or keys are malformed
    /// - Type references have empty names or excessive namespace lengths
    /// - Member references have empty or excessively long names
    fn validate_cross_assembly_references(&self, context: &OwnedValidationContext) -> Result<()> {
        // Check that the assembly object itself is valid
        if let Some(assembly) = context.object().assembly() {
            // Validate assembly name is not excessively long
            if assembly.name.len() > 1024 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly name is excessively long: {} characters",
                        assembly.name.len()
                    ),
                });
            }

            // Validate culture format if present
            if let Some(culture) = &assembly.culture {
                if !Self::is_valid_culture_format(culture) {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!("Assembly has invalid culture format: '{culture}'"),
                    });
                }
            }
        }

        // Validate external assembly references
        let assembly_refs = context.object().refs_assembly();
        for (index, entry) in assembly_refs.iter().enumerate() {
            let assembly_ref = entry.value();
            // Validate assembly reference name
            if assembly_ref.name.is_empty() {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!("Assembly reference {index} has empty name"),
                });
            }

            // Validate assembly reference name length
            if assembly_ref.name.len() > 1024 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly reference '{}' has excessively long name: {} characters",
                        assembly_ref.name,
                        assembly_ref.name.len()
                    ),
                });
            }

            // Validate culture format if present
            if let Some(culture) = &assembly_ref.culture {
                if !Self::is_valid_culture_format(culture) {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!(
                            "Assembly reference '{}' has invalid culture format: '{}'",
                            assembly_ref.name, culture
                        ),
                    });
                }
            }

            // Validate identity (public key/token) if present
            if let Some(identity) = &assembly_ref.identifier {
                match identity {
                    Identity::Token(token) => {
                        if *token == 0 {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' has empty public key token",
                                    assembly_ref.name
                                ),
                            });
                        }
                    }
                    Identity::PubKey(public_key) => {
                        if public_key.is_empty() {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' has empty public key",
                                    assembly_ref.name
                                ),
                            });
                        }
                        // Valid public key sizes per ECMA-335:
                        // - 16 bytes: ECMA keys for framework assemblies
                        // - 160+ bytes: Full RSA public keys for strong-named assemblies
                        if public_key.len() != 16
                            && (public_key.len() < 160 || public_key.len() > 2048)
                        {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' has invalid public key size: {} bytes. Expected 16 bytes (ECMA key) or 160-2048 bytes (RSA key)",
                                    assembly_ref.name,
                                    public_key.len()
                                ),

                            });
                        }
                    }
                    Identity::EcmaKey(ecma_key) => {
                        if ecma_key.len() != 16 {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' has invalid ECMA key size: {} bytes. Expected exactly 16 bytes",
                                    assembly_ref.name,
                                    ecma_key.len()
                                ),

                            });
                        }
                        if ecma_key.is_empty() || ecma_key.iter().all(|&b| b == 0) {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' has empty or invalid ECMA key",
                                    assembly_ref.name
                                ),
                            });
                        }
                    }
                }
            }
        }

        // Validate cross-assembly type references
        for type_entry in context.target_assembly_types() {
            let type_ref = type_entry.as_ref();
            // Only validate external type references
            if let Some(_external) = type_ref.get_external() {
                // Validate type reference has valid name
                if type_ref.name.is_empty() {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: "Cross-assembly type reference has empty name".to_string(),
                    });
                }

                // Validate namespace is reasonable
                if type_ref.namespace.len() > 512 {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!(
                            "Type reference '{}' has excessively long namespace: {} characters",
                            type_ref.name,
                            type_ref.namespace.len()
                        ),
                    });
                }
            }
        }

        // Validate cross-assembly member references
        let member_refs = context.object().refs_members();
        for entry in member_refs {
            let member_ref = entry.value();
            // Validate member reference has valid name
            if member_ref.name.is_empty() {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: "Cross-assembly member reference has empty name".to_string(),
                });
            }

            // Validate member name length
            if member_ref.name.len() > 512 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Member reference '{}' has excessively long name: {} characters",
                        member_ref.name,
                        member_ref.name.len()
                    ),
                });
            }
        }

        Ok(())
    }

    /// Validates assembly version compatibility and dependency validation.
    ///
    /// Ensures that assembly version dependencies are compatible and don't
    /// create impossible resolution scenarios or version conflicts.
    /// Validates version numbers and strong name consistency.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved assembly structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All assembly versions are compatible and consistent
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Version compatibility violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Assembly or reference versions are excessively high
    /// - Strong name tokens or public keys are malformed
    /// - Assembly reference flags contain unknown values
    fn validate_assembly_version_compatibility(
        &self,
        context: &OwnedValidationContext,
    ) -> Result<()> {
        // Validate the current assembly's version information
        if let Some(assembly) = context.object().assembly() {
            // Note: All-zero version (0.0.0.0) is valid and common for development assemblies
            // or assemblies that don't specify version information. We don't reject these.

            // Check for excessively high version numbers that might indicate corruption
            if assembly.major_version > 999
                || assembly.minor_version > 999
                || assembly.build_number > 65535
                || assembly.revision_number > 65535
            {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly '{}' has suspicious version numbers: {}.{}.{}.{}",
                        assembly.name,
                        assembly.major_version,
                        assembly.minor_version,
                        assembly.build_number,
                        assembly.revision_number
                    ),
                });
            }
        }

        // Validate assembly reference versions for compatibility
        let assembly_refs = context.object().refs_assembly();
        for entry in assembly_refs {
            let assembly_ref = entry.value();
            // Note: All-zero version (0.0.0.0) is valid for assembly references
            // Some assemblies don't specify version requirements for their dependencies.

            // Check for excessively high version numbers in dependencies
            if assembly_ref.major_version > 999
                || assembly_ref.minor_version > 999
                || assembly_ref.build_number > 65535
                || assembly_ref.revision_number > 65535
            {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly reference '{}' has suspicious version numbers: {}.{}.{}.{}",
                        assembly_ref.name,
                        assembly_ref.major_version,
                        assembly_ref.minor_version,
                        assembly_ref.build_number,
                        assembly_ref.revision_number
                    ),
                });
            }

            // Validate strong name consistency
            if let Some(identity) = &assembly_ref.identifier {
                match identity {
                    Identity::Token(token) => {
                        if *token == 0 {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' has zero public key token",
                                    assembly_ref.name
                                ),
                            });
                        }
                    }
                    Identity::PubKey(public_key) => {
                        if public_key.iter().all(|&b| b == 0) {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' public key consists entirely of zero bytes",
                                    assembly_ref.name
                                ),

                            });
                        }
                    }
                    Identity::EcmaKey(ecma_key) => {
                        if ecma_key.iter().all(|&b| b == 0) {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Assembly reference '{}' ECMA key consists entirely of zero bytes",
                                    assembly_ref.name
                                ),

                            });
                        }
                    }
                }
            }

            // Validate flags are reasonable
            if assembly_ref.flags > 0x0001 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly reference '{}' has unknown flags: 0x{:08X}",
                        assembly_ref.name, assembly_ref.flags
                    ),
                });
            }
        }

        Ok(())
    }

    /// Validates module and file consistency within assemblies.
    ///
    /// Ensures that modules and files are properly registered and consistent
    /// within the assembly structure. Validates module metadata and PE file structure.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved assembly structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All modules and files are consistent within the assembly
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Module file consistency violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Assembly flags or hash algorithm IDs are unknown
    /// - Module names are empty, excessively long, or have suspicious generation numbers
    /// - Module IDs (MVIDs) are all-zero
    /// - PE file size is suspiciously small or excessively large
    fn validate_module_file_consistency(&self, context: &OwnedValidationContext) -> Result<()> {
        // Validate basic assembly structure
        if let Some(assembly) = context.object().assembly() {
            // Check that assembly has reasonable flags
            if assembly.flags > 0x0001 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly '{}' has unknown flags: 0x{:08X}",
                        assembly.name, assembly.flags
                    ),
                });
            }

            // Validate hash algorithm is reasonable
            if assembly.hash_alg_id != 0
                && assembly.hash_alg_id != 0x8003
                && assembly.hash_alg_id != 0x8004
                && assembly.hash_alg_id != 0x800C
            {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Assembly '{}' has unknown hash algorithm: 0x{:08X}",
                        assembly.name, assembly.hash_alg_id
                    ),
                });
            }
        }

        // Validate modules within the assembly
        if let Some(module) = context.object().module() {
            let index = 0;
            // Validate module name
            if module.name.is_empty() {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!("Module {index} has empty name"),
                });
            }

            // Validate module name length
            if module.name.len() > 260 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Module '{}' has excessively long name: {} characters",
                        module.name,
                        module.name.len()
                    ),
                });
            }

            // Validate module generation is reasonable
            if module.generation > 65535 {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Module '{}' has suspicious generation number: {}",
                        module.name, module.generation
                    ),
                });
            }

            // Validate module ID is not all zeros
            if module.mvid.to_bytes().iter().all(|&b| b == 0) {
                return Err(Error::ValidationOwnedFailed {
                    validator: self.name().to_string(),
                    message: format!(
                        "Module '{}' has all-zero MVID (Module Version ID)",
                        module.name
                    ),
                });
            }
        }

        // Validate PE file structure
        let file = context.object().file();
        let file_data = file.data();

        // Basic PE file validation
        if file_data.len() < 1024 {
            return Err(Error::ValidationOwnedFailed {
                validator: self.name().to_string(),
                message: "Assembly file is suspiciously small (< 1024 bytes)".to_string(),
            });
        }

        // Check for reasonable PE file size (not corrupted)
        if file_data.len() > 100_000_000 {
            // 100MB limit
            return Err(Error::ValidationOwnedFailed {
                validator: self.name().to_string(),
                message: format!(
                    "Assembly file is excessively large: {} bytes",
                    file_data.len()
                ),
            });
        }

        Ok(())
    }
}

impl OwnedValidator for OwnedAssemblyValidator {
    fn validate_owned(&self, context: &OwnedValidationContext) -> Result<()> {
        self.validate_assembly_metadata_consistency(context)?;
        self.validate_cross_assembly_references(context)?;
        self.validate_assembly_version_compatibility(context)?;
        self.validate_module_file_consistency(context)?;

        Ok(())
    }

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

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

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

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

#[cfg(test)]
#[cfg_attr(feature = "skip-expensive-tests", allow(unused_imports))]
mod tests {
    use super::*;
    use crate::{
        metadata::validation::ValidationConfig,
        test::{
            factories::validation::system_assembly::owned_assembly_validator_file_factory,
            owned_validator_test,
        },
    };

    #[test]
    #[cfg(not(feature = "skip-expensive-tests"))]
    fn test_owned_assembly_validator() -> Result<()> {
        let validator = OwnedAssemblyValidator::new();
        let config = ValidationConfig {
            enable_semantic_validation: true,
            ..Default::default()
        };

        owned_validator_test(
            owned_assembly_validator_file_factory,
            "OwnedAssemblyValidator",
            "ValidationOwnedFailed",
            config,
            |context| validator.validate_owned(context),
        )
    }
}