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
//! Owned field validator for field validation and layout rules.
//!
//! This validator provides comprehensive validation of field definitions, accessibility,
//! layout constraints, and signature consistency within the context of fully resolved
//! .NET metadata. It operates on resolved field structures to ensure ECMA-335 compliance
//! for field declarations and type system consistency. This validator runs with priority 155
//! in the owned validation stage.
//!
//! # Architecture
//!
//! The field validation system implements comprehensive field validation in sequential order:
//! 1. **Field Signature Validation** - Ensures field signatures are well-formed and types are resolved
//! 2. **Field Accessibility Validation** - Validates access modifiers and inheritance compatibility
//! 3. **Special Attributes Validation** - Validates special field attributes and constraints
//! 4. **Field Naming Validation** - Ensures field naming conventions and special patterns
//!
//! The implementation validates field constraints according to ECMA-335 specifications,
//! ensuring proper field definitions across type hierarchies and member relationships.
//! All validation includes signature checking and accessibility rule verification.
//!
//! # Key Components
//!
//! - [`crate::metadata::validation::validators::owned::members::field::OwnedFieldValidator`] - Main validator implementation providing comprehensive field validation
//! - [`crate::metadata::validation::validators::owned::members::field::OwnedFieldValidator::validate_field_signatures`] - Field signature consistency and type resolution validation
//! - [`crate::metadata::validation::validators::owned::members::field::OwnedFieldValidator::validate_field_accessibility`] - Field accessibility and inheritance rule validation
//! - [`crate::metadata::validation::validators::owned::members::field::OwnedFieldValidator::validate_special_attributes`] - Special field attribute validation (HasDefault, HasFieldRVA, etc.)
//! - [`crate::metadata::validation::validators::owned::members::field::OwnedFieldValidator::validate_field_naming`] - Field naming convention validation
//!
//! # Usage Examples
//!
//! ```rust,no_run
//! use dotscope::metadata::validation::{OwnedFieldValidator, OwnedValidator, OwnedValidationContext};
//!
//! # fn get_context() -> OwnedValidationContext<'static> { unimplemented!() }
//! let context = get_context();
//! let validator = OwnedFieldValidator::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:
//! - Field signature consistency violations (empty names, unresolved types)
//! - Invalid field accessibility levels (unknown access modifiers)
//! - Field attribute constraint violations (literal fields not static)
//! - Special attribute inconsistencies (RTSpecialName without SpecialName)
//! - Field naming convention violations (backing fields not private, null characters)
//! - Type signature resolution failures (Unknown type signatures)
//! - Field modifier validation failures (invalid tokens)
//!
//! # 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:
//! - [`crate::metadata::validation::validators::owned::members`] - Part of the owned member 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 field 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.22.15](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Field table specification
//! - [ECMA-335 II.23.1.5](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - FieldAttributes specification
//! - [ECMA-335 II.10.7](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Field layout and packing
//! - [ECMA-335 II.16](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Field initialization and constants

use crate::{
    metadata::{
        tables::FieldAttributes,
        validation::{
            context::{OwnedValidationContext, ValidationContext},
            traits::OwnedValidator,
        },
    },
    Error, Result,
};

/// Foundation validator for field definitions, accessibility rules, and layout constraints.
///
/// Ensures the structural integrity and consistency of field definitions in resolved .NET metadata,
/// validating proper field signatures, accessibility patterns, and special attribute usage.
/// This validator operates on resolved field structures to provide essential guarantees
/// about field compliance with ECMA-335 specifications.
///
/// The validator implements comprehensive coverage of field validation according to
/// ECMA-335 specifications, ensuring proper field definitions across type hierarchies
/// and member relationships 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 OwnedFieldValidator;

impl OwnedFieldValidator {
    /// Creates a new field validator instance.
    ///
    /// Initializes a validator instance that can be used to validate field definitions
    /// across multiple assemblies. The validator is stateless and can be reused safely
    /// across multiple validation operations.
    ///
    /// # Returns
    ///
    /// A new [`crate::metadata::validation::validators::owned::members::field::OwnedFieldValidator`] 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 field signature consistency and type resolution.
    ///
    /// Ensures that all field signatures are well-formed and that field types
    /// are properly resolved according to ECMA-335 specifications. Validates
    /// field names and signature modifiers.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved field structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All field signatures are valid and resolved
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Field signature violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Field names are empty
    /// - Field signatures contain unresolved types (Unknown type signatures)
    /// - Field modifiers have invalid tokens
    fn validate_field_signatures(&self, context: &OwnedValidationContext) -> Result<()> {
        for type_entry in context.all_types() {
            for (_, field) in type_entry.fields.iter() {
                if field.name.is_empty() {
                    let token_value = field.token.value();
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!("Field with token 0x{token_value:08X} has empty name"),
                    });
                }

                if let crate::metadata::signatures::TypeSignature::Unknown = &field.signature.base {
                    let field_name = &field.name;
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!("Field '{field_name}' has unresolved type in signature"),
                    });
                }

                for (index, modifier) in field.signature.modifiers.iter().enumerate() {
                    if modifier.modifier_type.value() == 0 {
                        let field_name = &field.name;
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Field '{field_name}' modifier {index} has invalid token"
                            ),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Validates field accessibility and inheritance rules.
    ///
    /// Ensures that field access modifiers are valid and compatible with
    /// inheritance patterns and type accessibility. Validates literal field
    /// requirements and access level consistency.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved field structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All field accessibility rules are valid
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Field accessibility violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Field access levels contain invalid values
    /// - Literal fields are not marked as static (ECMA-335 requirement)
    fn validate_field_accessibility(&self, context: &OwnedValidationContext) -> Result<()> {
        for type_entry in context.all_types() {
            for (_, field) in type_entry.fields.iter() {
                let access_level = field.flags & FieldAttributes::FIELD_ACCESS_MASK;

                match access_level {
                    FieldAttributes::COMPILER_CONTROLLED
                    | FieldAttributes::PRIVATE
                    | FieldAttributes::FAM_AND_ASSEM
                    | FieldAttributes::ASSEMBLY
                    | FieldAttributes::FAMILY
                    | FieldAttributes::FAM_OR_ASSEM
                    | FieldAttributes::PUBLIC => {
                        // Valid access level
                    }
                    _ => {
                        let field_name = &field.name;
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Field '{field_name}' has invalid access level: 0x{access_level:02X}"
                            ),

                        });
                    }
                }

                if field.flags & FieldAttributes::STATIC != 0
                    && field.flags & FieldAttributes::INIT_ONLY != 0
                {
                    // This is actually valid - static readonly fields are allowed
                    // No error here
                }

                if field.flags & 0x0040 != 0 && field.flags & FieldAttributes::STATIC == 0 {
                    let field_name = &field.name;
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!("Literal field '{field_name}' must also be static"),
                    });
                }
            }
        }

        Ok(())
    }

    /// Validates special field attributes and constraints.
    ///
    /// Ensures that special field attributes like HasDefault, HasFieldRVA, and
    /// HasFieldMarshal are used correctly and consistently. Validates RTSpecialName
    /// and SpecialName flag combinations.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved field structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All special field attributes are valid
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Special attribute violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - RTSpecialName flag is set without SpecialName flag
    fn validate_special_attributes(&self, context: &OwnedValidationContext) -> Result<()> {
        for type_entry in context.all_types() {
            for (_, field) in type_entry.fields.iter() {
                // Check HasDefault flag consistency
                if field.flags & 0x1000 != 0 { // HAS_DEFAULT flag
                     // Field claims to have default value - this is generally valid
                     // The actual default value validation would require accessing the Constant table
                }

                // Check HasFieldRVA flag consistency
                if field.flags & 0x0080 != 0 {
                    // HAS_FIELD_RVA flag
                    // Field should have RVA - typically for static fields with initial data
                    // However, in legitimate .NET assemblies, instance fields can also have this flag
                    // for specific purposes (synchronization objects, fixed buffers, etc.)
                    // So we allow this pattern and only validate the flag exists
                }

                // Check HasFieldMarshal flag
                if field.flags & 0x2000 != 0 { // HAS_FIELD_MARSHAL flag
                     // Field has marshalling information - this is valid for P/Invoke scenarios
                     // No specific validation needed here
                }

                // Check NotSerialized flag
                if field.flags & 0x0040 != 0 { // NOT_SERIALIZED flag (different from LITERAL)
                     // Field is marked as not serialized - this is valid
                     // No specific validation needed
                }

                // Check RTSpecialName flag (if present)
                if field.flags & 0x0400 != 0 {
                    // RT_SPECIAL_NAME flag
                    // Field has special meaning to runtime
                    // Often paired with SpecialName
                    if field.flags & 0x0200 == 0 {
                        // SPECIAL_NAME flag
                        let field_name = &field.name;
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Field '{field_name}' has RTSpecialName but not SpecialName"
                            ),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Validates field naming conventions and special patterns.
    ///
    /// Ensures that fields follow appropriate naming conventions, especially
    /// for compiler-generated and special-purpose fields. Validates backing
    /// field accessibility and naming character constraints.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved field structures via [`crate::metadata::validation::context::OwnedValidationContext`]
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All field naming conventions are valid
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Field naming violations found
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::ValidationOwnedFailed`] if:
    /// - Backing fields are not marked as private
    /// - Field names contain null characters
    fn validate_field_naming(&self, context: &OwnedValidationContext) -> Result<()> {
        for type_entry in context.all_types() {
            for (_, field) in type_entry.fields.iter() {
                if field.name.starts_with('<') && field.name.ends_with(">k__BackingField") {
                    let access_level = field.flags & FieldAttributes::FIELD_ACCESS_MASK;
                    if access_level != FieldAttributes::PRIVATE {
                        let field_name = &field.name;
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!("Backing field '{field_name}' should be private"),
                        });
                    }
                }

                if field.name.starts_with('<')
                    && field.name.contains("Event")
                    && field.flags & FieldAttributes::STATIC == 0
                {
                    let access_level = field.flags & FieldAttributes::FIELD_ACCESS_MASK;
                    if access_level == FieldAttributes::PUBLIC {}
                }

                if field.name.contains('\0') {
                    let field_name = &field.name;
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!("Field '{field_name}' contains null character"),
                    });
                }
            }
        }

        Ok(())
    }
}

impl OwnedValidator for OwnedFieldValidator {
    fn validate_owned(&self, context: &OwnedValidationContext) -> Result<()> {
        self.validate_field_signatures(context)?;
        self.validate_field_accessibility(context)?;
        self.validate_special_attributes(context)?;
        self.validate_field_naming(context)?;

        Ok(())
    }

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

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

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

impl Default for OwnedFieldValidator {
    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::members_field::owned_field_validator_file_factory,
            owned_validator_test,
        },
    };

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

        owned_validator_test(
            owned_field_validator_file_factory,
            "OwnedFieldValidator",
            "ValidationOwnedFailed",
            config,
            |context| validator.validate_owned(context),
        )
    }
}