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
//! Owned dependency validator for dependency chain validation in resolved metadata.
//!
//! This validator provides comprehensive validation of dependency chains within the context
//! of fully resolved .NET metadata. It operates on resolved type structures to validate
//! dependency graph integrity, transitive dependency satisfaction, and proper dependency
//! ordering for semantic correctness. This validator runs with priority 140
//! in the owned validation stage.
//!
//! # Architecture
//!
//! The dependency validation system implements comprehensive dependency chain validation in sequential order:
//! 1. **Dependency Graph Construction** - Builds complete dependency graphs from resolved type relationships
//! 2. **Transitive Dependency Validation** - Validates all semantic dependencies are satisfied across assemblies
//! 3. **Broken Chain Detection** - Identifies broken dependency chains in type hierarchies
//! 4. **Dependency Ordering Validation** - Ensures proper dependency ordering for inheritance and composition
//!
//! The implementation validates dependency constraints according to ECMA-335 specifications,
//! ensuring proper type relationship formation and dependency satisfaction.
//! All validation includes graph construction and transitive dependency analysis.
//!
//! # Key Components
//!
//! - [`crate::metadata::validation::validators::owned::relationships::dependency::OwnedDependencyValidator`] - Main validator implementation providing comprehensive dependency validation
//!
//! # Usage Examples
//!
//! ```rust,no_run
//! use dotscope::metadata::validation::{OwnedDependencyValidator, OwnedValidator, OwnedValidationContext};
//!
//! # fn get_context() -> OwnedValidationContext<'static> { unimplemented!() }
//! let context = get_context();
//! let validator = OwnedDependencyValidator::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:
//! - Broken dependency chains in type hierarchies (missing required dependencies)
//! - Unsatisfied transitive dependencies across assemblies (unresolved type references)
//! - Invalid dependency ordering for inheritance and composition (circular dependencies)
//! - Cross-assembly dependency resolution failures (broken external references)
//!
//! # 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::relationships`] - Part of the owned relationship 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 type structures
//! - [`crate::metadata::validation::context::OwnedValidationContext`] - Provides validation execution context
//! - [`crate::metadata::validation::config::ValidationConfig`] - Controls validation execution via enable_cross_table_validation flag
//!
//! # References
//!
//! - [ECMA-335 II.10](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - Type system and inheritance dependencies
//! - [ECMA-335 II.22.37](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - TypeDef table and type dependencies
//! - [ECMA-335 II.22.38](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) - TypeRef table and external dependencies

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

/// Foundation validator for dependency chain validation in resolved metadata structures.
///
/// Ensures the structural integrity and consistency of dependency relationships in resolved .NET metadata,
/// validating that dependency graphs are well-formed, transitive dependencies are satisfied,
/// and dependency ordering follows semantic correctness rules. This validator operates on resolved
/// type structures to provide essential guarantees about dependency chain integrity.
///
/// The validator implements comprehensive coverage of dependency validation according to
/// ECMA-335 specifications, ensuring proper type relationship dependencies and cross-assembly
/// reference satisfaction 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 OwnedDependencyValidator;

impl OwnedDependencyValidator {
    /// Creates a new dependency validator instance.
    ///
    /// Initializes a validator instance that can be used to validate dependency chains
    /// across multiple assemblies. The validator is stateless and can be reused safely
    /// across multiple validation operations.
    ///
    /// # Returns
    ///
    /// A new [`crate::metadata::validation::validators::owned::relationships::dependency::OwnedDependencyValidator`] 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 dependency graph integrity across all type relationships.
    ///
    /// Ensures that the dependency graph formed by type relationships is well-formed
    /// and doesn't contain broken links or inconsistent references.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved type structures
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Dependency graph integrity is valid
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Graph integrity violations found
    fn validate_dependency_graph_integrity(&self, context: &OwnedValidationContext) -> Result<()> {
        for type_entry in context.target_assembly_types() {
            // Validate base type dependencies
            if let Some(base_type) = type_entry.base() {
                if base_type.name.is_empty() {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!(
                            "Type '{}' has broken base type dependency (empty name)",
                            type_entry.name
                        ),
                    });
                }
            }

            // Validate interface dependencies
            for (_, interface_ref) in type_entry.interfaces.iter() {
                if let Some(interface_type) = interface_ref.upgrade() {
                    if interface_type.name.is_empty() {
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Type '{}' has broken interface dependency (empty name)",
                                type_entry.name
                            ),
                        });
                    }
                } else {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!(
                            "Type '{}' has broken interface dependency reference",
                            type_entry.name
                        ),
                    });
                }
            }

            // Validate nested type dependencies
            for (_, nested_ref) in type_entry.nested_types.iter() {
                if let Some(nested_type) = nested_ref.upgrade() {
                    if nested_type.name.is_empty() {
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Type '{}' has broken nested type dependency (empty name)",
                                type_entry.name
                            ),
                        });
                    }
                } else {
                    return Err(Error::ValidationOwnedFailed {
                        validator: self.name().to_string(),
                        message: format!(
                            "Type '{}' has broken nested type dependency reference",
                            type_entry.name
                        ),
                    });
                }
            }

            // Validate generic parameter dependencies
            for (_, generic_param) in type_entry.generic_params.iter() {
                for (_, constraint_ref) in generic_param.constraints.iter() {
                    if let Some(constraint_type) = constraint_ref.upgrade() {
                        if constraint_type.name.is_empty() {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Type '{}' generic parameter '{}' has broken constraint dependency (empty name)",
                                    type_entry.name, generic_param.name
                                ),

                            });
                        }
                    } else {
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Type '{}' generic parameter '{}' has broken constraint dependency reference",
                                type_entry.name, generic_param.name
                            ),

                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Validates transitive dependency satisfaction across all dependencies.
    ///
    /// Ensures that all transitive dependencies are satisfied and that dependency
    /// chains are complete throughout the type system.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved type structures
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All transitive dependencies are satisfied
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Transitive dependency violations found
    fn validate_transitive_dependency_satisfaction(
        &self,
        context: &OwnedValidationContext,
    ) -> Result<()> {
        let methods = context.object().methods();

        // Build complete dependency graph
        let mut dependency_graph = rustc_hash::FxHashMap::default();
        for type_entry in context.target_assembly_types() {
            let token = type_entry.token;
            let mut dependencies = Vec::new();

            // Add direct dependencies
            if let Some(base_type) = type_entry.base() {
                dependencies.push(base_type.token);
            }

            for (_, interface_ref) in type_entry.interfaces.iter() {
                if let Some(interface_type) = interface_ref.upgrade() {
                    dependencies.push(interface_type.token);
                }
            }

            for (_, nested_ref) in type_entry.nested_types.iter() {
                if let Some(nested_type) = nested_ref.upgrade() {
                    dependencies.push(nested_type.token);
                }
            }

            dependency_graph.insert(token, dependencies);
        }

        // Validate method dependencies
        for type_entry in context.target_assembly_types() {
            for (_, method_ref) in type_entry.methods.iter() {
                if let Some(method_token) = method_ref.token() {
                    if let Some(method) = methods.get(&method_token) {
                        // Validate parameter type dependencies
                        for (index, (_, param)) in method.value().params.iter().enumerate() {
                            if let Some(param_type_ref) = param.base.get() {
                                if param_type_ref.upgrade().is_none() {
                                    return Err(Error::ValidationOwnedFailed {
                                        validator: self.name().to_string(),
                                        message: format!(
                                            "Method '{}' in type '{}' has broken parameter {} type dependency",
                                            method.value().name, type_entry.name, index
                                        ),

                                    });
                                }
                            }
                        }

                        // Validate local variable type dependencies
                        for (index, (_, local)) in method.value().local_vars.iter().enumerate() {
                            if local.base.upgrade().is_none() {
                                return Err(Error::ValidationOwnedFailed {
                                    validator: self.name().to_string(),
                                    message: format!(
                                        "Method '{}' in type '{}' has broken local variable {} type dependency",
                                        method.value().name, type_entry.name, index
                                    ),

                                });
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Validates dependency ordering for inheritance and composition.
    ///
    /// Ensures that dependencies are ordered correctly to prevent loading issues
    /// and that composition relationships don't violate semantic rules.
    ///
    /// # Arguments
    ///
    /// * `context` - Owned validation context containing resolved type structures
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Dependency ordering is correct
    /// * `Err(`[`crate::Error::ValidationOwnedFailed`]`)` - Dependency ordering violations found
    fn validate_dependency_ordering(&self, context: &OwnedValidationContext) -> Result<()> {
        for type_entry in context.target_assembly_types() {
            // Validate inheritance ordering
            if let Some(base_type) = type_entry.base() {
                // Check for self-referential inheritance
                // IMPORTANT: Only flag self-reference if both types are from the same assembly.
                // Tokens are only unique within an assembly, so we need to check assembly context.
                // A type is local (from target assembly) if get_external() returns None.
                // A type is external if get_external() returns Some(...).
                if base_type.token == type_entry.token {
                    let type_is_local = type_entry.get_external().is_none();
                    let base_is_local = base_type.get_external().is_none();

                    // Only flag self-reference if both are local (same assembly)
                    // or both are external from the same source
                    let is_same_assembly = match (type_is_local, base_is_local) {
                        (true, true) => true, // Both local to target assembly
                        // Both external or one local/one external - different assemblies
                        _ => false,
                    };

                    if is_same_assembly {
                        return Err(Error::ValidationOwnedFailed {
                            validator: self.name().to_string(),
                            message: format!(
                                "Type '{}' has self-referential inheritance dependency",
                                type_entry.name
                            ),
                        });
                    }
                }

                // Validate that base type is loaded/resolvable before derived type
                // This is mainly a logical consistency check for resolved metadata
                if base_type.fullname().is_empty() && !base_type.name.is_empty() {
                    // Base type might be partially resolved - this could indicate ordering issues
                    // But allow it for now as external types may not have full names
                }
            }

            // Validate interface implementation ordering
            for (_, interface_ref) in type_entry.interfaces.iter() {
                if let Some(interface_type) = interface_ref.upgrade() {
                    // Check for self-referential interface implementation
                    // Only flag if both types are from the same assembly
                    if interface_type.token == type_entry.token {
                        let type_is_local = type_entry.get_external().is_none();
                        let interface_is_local = interface_type.get_external().is_none();

                        let is_same_assembly =
                            matches!((type_is_local, interface_is_local), (true, true));

                        if is_same_assembly {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Type '{}' has self-referential interface implementation dependency",
                                    type_entry.name
                                ),

                            });
                        }
                    }
                }
            }

            // Validate nested type ordering
            for (_, nested_ref) in type_entry.nested_types.iter() {
                if let Some(nested_type) = nested_ref.upgrade() {
                    // Check for self-referential nested type containment
                    // Only flag if both types are from the same assembly
                    if nested_type.token == type_entry.token {
                        let type_is_local = type_entry.get_external().is_none();
                        let nested_is_local = nested_type.get_external().is_none();

                        let is_same_assembly =
                            matches!((type_is_local, nested_is_local), (true, true));

                        if is_same_assembly {
                            return Err(Error::ValidationOwnedFailed {
                                validator: self.name().to_string(),
                                message: format!(
                                    "Type '{}' has self-referential nested type dependency",
                                    type_entry.name
                                ),
                            });
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

impl OwnedValidator for OwnedDependencyValidator {
    fn validate_owned(&self, context: &OwnedValidationContext) -> Result<()> {
        self.validate_dependency_graph_integrity(context)?;
        self.validate_transitive_dependency_satisfaction(context)?;
        self.validate_dependency_ordering(context)?;

        Ok(())
    }

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

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

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

impl Default for OwnedDependencyValidator {
    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::dependency::owned_dependency_validator_file_factory,
            owned_validator_test,
        },
    };

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

        owned_validator_test(
            owned_dependency_validator_file_factory,
            "OwnedDependencyValidator",
            "ValidationOwnedFailed",
            config,
            |context| validator.validate_owned(context),
        )
    }
}