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
//! Conflict resolution strategies for assembly modification operations.
//!
//! This module provides conflict resolution strategies for handling conflicting operations
//! during assembly modification. When multiple operations target the same metadata
//! element, resolvers determine which operation should take precedence.
//!
//! # Key Components
//!
//! - [`LastWriteWinsResolver`] - Default conflict resolver using timestamp ordering
//! - [`ConflictResolver`] - Trait for implementing custom resolution strategies
//! - [`Conflict`] - Types of conflicts that can occur during modification
//! - [`Resolution`] - Conflict resolution results
//!
//! # Architecture
//!
//! The conflict resolution system is built around pluggable strategies that can be
//! configured based on application requirements:
//!
//! ## Timestamp-Based Resolution
//! The default [`LastWriteWinsResolver`] uses operation timestamps to determine
//! precedence, with later operations overriding earlier ones.
//!
//! ## Extensible Design
//! The [`ConflictResolver`] trait allows custom resolution strategies
//! to be implemented for specific use cases.
//!
//! # Usage Examples
//!
//! ```rust,ignore
//! use crate::cilassembly::resolver::{LastWriteWinsResolver, ConflictResolver, Conflict};
//!
//! // Create a resolver
//! let resolver = LastWriteWinsResolver;
//!
//! // Resolve conflicts (typically used by validation pipeline)
//! // let conflicts = vec![/* conflicts */];
//! // let resolution = resolver.resolve_conflict(&conflicts)?;
//! # Ok::<(), crate::Error>(())
//! ```
//!
//! # Thread Safety
//!
//! This type is [`Send`] and [`Sync`] as it contains no mutable state and operates
//! purely on the input data.

use crate::{cilassembly::TableOperation, Error, Result};
use std::collections::HashMap;

/// Trait for conflict resolution strategies.
///
/// Different applications may need different conflict resolution strategies:
/// - **Last-write-wins (default)**: Most recent operation takes precedence
/// - **First-write-wins**: First operation takes precedence
/// - **Merge operations**: Combine compatible operations
/// - **Reject on conflict**: Fail validation on any conflict
///
/// Conflict resolution is essential for handling scenarios where multiple
/// operations target the same resource, ensuring deterministic behavior
/// and maintaining assembly integrity.
///
/// # Implementation Guidelines
///
/// Conflict resolvers should:
/// - Be deterministic and consistent
/// - Handle all conflict types appropriately
/// - Provide clear resolution decisions
/// - Be configurable for different use cases
/// - Maintain operation ordering guarantees
///
/// # Examples
///
/// ```rust,ignore
/// use crate::cilassembly::resolver::{ConflictResolver, Conflict, Resolution};
///
/// struct LastWriteWinsResolver;
///
/// impl ConflictResolver for LastWriteWinsResolver {
///     fn resolve_conflict(&self, conflicts: &[Conflict]) -> Result<Resolution> {
///         let mut resolution = Resolution::default();
///         for conflict in conflicts {
///             // Resolve by choosing the latest operation
///             // Implementation details...
///         }
///         Ok(resolution)
///     }
/// }
/// ```
pub trait ConflictResolver {
    /// Resolves conflicts between operations.
    ///
    /// This method analyzes the provided conflicts and determines how to resolve
    /// them according to the resolver's strategy. The resolution specifies which
    /// operations should be applied and in what order.
    ///
    /// # Arguments
    ///
    /// * `conflicts` - Array of [`Conflict`] instances representing conflicting operations
    ///
    /// # Returns
    ///
    /// Returns a [`Resolution`] that specifies how to handle each conflict,
    /// including which operations to apply and which to reject.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if conflicts cannot be resolved or if the
    /// resolution strategy encounters invalid conflict states.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use crate::cilassembly::resolver::{ConflictResolver, Conflict};
    ///
    /// # let resolver = LastWriteWinsResolver;
    /// # let conflicts = vec![]; // conflicts would be populated
    /// let resolution = resolver.resolve_conflict(&conflicts)?;
    /// for (rid, operation_resolution) in resolution.operations {
    ///     println!("RID {} resolved to: {:?}", rid, operation_resolution);
    /// }
    /// # Ok::<(), crate::Error>(())
    /// ```
    fn resolve_conflict(&self, conflicts: &[Conflict]) -> Result<Resolution>;
}

/// Types of conflicts that can occur during modification.
///
/// Conflicts arise when multiple operations target the same resource
/// or when operations have incompatible effects.
#[derive(Debug)]
pub enum Conflict {
    /// Multiple operations targeting the same RID.
    ///
    /// This occurs when multiple operations (insert, update, delete)
    /// are applied to the same table row.
    MultipleOperationsOnRid {
        /// The RID being modified.
        rid: u32,
        /// The conflicting operations.
        operations: Vec<TableOperation>,
    },

    /// Insert and delete operations on the same RID.
    ///
    /// This specific conflict occurs when a row is both inserted
    /// and deleted, which requires special resolution logic.
    InsertDeleteConflict {
        /// The RID being modified.
        rid: u32,
        /// The insert operation.
        insert_op: TableOperation,
        /// The delete operation.
        delete_op: TableOperation,
    },
}

/// Resolution of conflicts.
///
/// Contains the final resolved operations after conflict resolution.
/// This structure is used to apply the resolved operations to the assembly.
#[derive(Debug, Default)]
pub struct Resolution {
    /// Resolved operations keyed by RID.
    pub operations: HashMap<u32, OperationResolution>,
}

/// How to resolve a specific operation conflict.
///
/// Specifies the action to take for a conflicted operation.
#[derive(Debug)]
pub enum OperationResolution {
    /// Use the specified operation.
    UseOperation(TableOperation),
    /// Use the chronologically latest operation.
    UseLatest,
    /// Merge multiple operations into a sequence.
    Merge(Vec<TableOperation>),
    /// Reject the operation with an error message.
    Reject(String),
}

/// Default last-write-wins conflict resolver.
///
/// [`LastWriteWinsResolver`] implements a simple conflict resolution strategy that uses
/// operation timestamps to determine precedence. When multiple operations target the same
/// metadata element, the operation with the latest timestamp takes precedence.
///
/// This resolver handles two types of conflicts:
/// - **Multiple Operations on RID**: When several operations target the same table row
/// - **Insert/Delete Conflicts**: When both insert and delete operations target the same RID
///
/// # Usage Examples
///
/// ```rust,ignore
/// use crate::cilassembly::resolver::{LastWriteWinsResolver, ConflictResolver, Conflict};
///
/// let resolver = LastWriteWinsResolver;
///
/// // Typically used by validation pipeline
/// // let conflicts = vec![/* detected conflicts */];
/// // let resolution = resolver.resolve_conflict(&conflicts)?;
/// # Ok::<(), crate::Error>(())
/// ```
///
/// # Thread Safety
///
/// This type is [`Send`] and [`Sync`] as it contains no state and operates purely on
/// the input data provided to the resolution methods.
pub struct LastWriteWinsResolver;

impl ConflictResolver for LastWriteWinsResolver {
    /// Resolves conflicts using last-write-wins strategy.
    ///
    /// This method processes an array of conflicts and determines the winning operation
    /// for each conflicted RID based on timestamp ordering. For each conflict, the
    /// operation with the latest timestamp is selected as the winner.
    ///
    /// # Tie-Breaking Behavior
    ///
    /// When two operations have identical timestamps:
    /// - For `MultipleOperationsOnRid`: The first operation encountered with the maximum
    ///   timestamp wins (deterministic based on vector order).
    /// - For `InsertDeleteConflict`: Insert operations win over Delete operations when
    ///   timestamps are equal (using `>=` comparison). This favors data preservation.
    ///
    /// # Arguments
    ///
    /// * `conflicts` - Array of [`Conflict`] instances to resolve
    ///
    /// # Returns
    ///
    /// Returns a [`Resolution`] containing the winning operation
    /// for each conflicted RID.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if resolution processing fails, though this implementation
    /// is designed to always succeed with valid input.
    fn resolve_conflict(&self, conflicts: &[Conflict]) -> Result<Resolution> {
        let mut resolution_map = HashMap::new();

        for conflict in conflicts {
            match conflict {
                Conflict::MultipleOperationsOnRid { rid, operations } => {
                    if let Some(latest_op) = operations.iter().max_by_key(|op| op.timestamp) {
                        resolution_map
                            .insert(*rid, OperationResolution::UseOperation(latest_op.clone()));
                    }
                }
                Conflict::InsertDeleteConflict {
                    rid,
                    insert_op,
                    delete_op,
                } => {
                    if !insert_op.is_insert() {
                        return Err(Error::ConflictResolution(format!(
                            "InsertDeleteConflict for RID {rid}: insert_op is not an Insert operation"
                        )));
                    }
                    if !delete_op.is_delete() {
                        return Err(Error::ConflictResolution(format!(
                            "InsertDeleteConflict for RID {rid}: delete_op is not a Delete operation"
                        )));
                    }

                    let winning_op = if insert_op.timestamp >= delete_op.timestamp {
                        insert_op
                    } else {
                        delete_op
                    };
                    resolution_map
                        .insert(*rid, OperationResolution::UseOperation(winning_op.clone()));
                }
            }
        }

        Ok(Resolution {
            operations: resolution_map,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{cilassembly::Operation, test::factories::table::cilassembly::create_test_row};

    #[test]
    fn test_last_write_wins_resolver_multiple_operations() {
        let operations = vec![
            {
                let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
                op.timestamp = 1000; // Microseconds since epoch
                op
            },
            {
                let mut op = TableOperation::new(Operation::Update(100, create_test_row()));
                op.timestamp = 2000; // Later timestamp
                op
            },
        ];

        let conflict = Conflict::MultipleOperationsOnRid {
            rid: 100,
            operations,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]);
        assert!(result.is_ok(), "Conflict resolution should succeed");

        if let Ok(resolution) = result {
            assert!(
                resolution.operations.contains_key(&100),
                "Should resolve RID 100"
            );

            if let Some(OperationResolution::UseOperation(op)) = resolution.operations.get(&100) {
                assert!(
                    matches!(op.operation, Operation::Update(100, _)),
                    "Should use Update operation"
                );
            } else {
                panic!("Expected UseOperation resolution");
            }
        }
    }

    #[test]
    fn test_last_write_wins_resolver_single_operation_in_conflict() {
        // Edge case: only one operation in the conflict vector
        let operations = vec![{
            let mut op = TableOperation::new(Operation::Delete(50));
            op.timestamp = 5000;
            op
        }];

        let conflict = Conflict::MultipleOperationsOnRid {
            rid: 50,
            operations,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]).unwrap();

        assert!(result.operations.contains_key(&50));
        if let Some(OperationResolution::UseOperation(op)) = result.operations.get(&50) {
            assert!(matches!(op.operation, Operation::Delete(50)));
            assert_eq!(op.timestamp, 5000);
        } else {
            panic!("Expected UseOperation resolution");
        }
    }

    #[test]
    fn test_last_write_wins_resolver_equal_timestamps() {
        // Edge case: equal timestamps - should still resolve (first one with max_by_key)
        let operations = vec![
            {
                let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
                op.timestamp = 1000;
                op
            },
            {
                let mut op = TableOperation::new(Operation::Update(100, create_test_row()));
                op.timestamp = 1000; // Same timestamp
                op
            },
        ];

        let conflict = Conflict::MultipleOperationsOnRid {
            rid: 100,
            operations,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]);
        assert!(result.is_ok(), "Should handle equal timestamps");

        let resolution = result.unwrap();
        assert!(resolution.operations.contains_key(&100));
    }

    #[test]
    fn test_last_write_wins_resolver_insert_delete_conflict() {
        let insert_op = {
            let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
            op.timestamp = 1000; // Microseconds since epoch
            op
        };

        let delete_op = {
            let mut op = TableOperation::new(Operation::Delete(100));
            op.timestamp = 2000; // Later timestamp
            op
        };

        let conflict = Conflict::InsertDeleteConflict {
            rid: 100,
            insert_op,
            delete_op,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]);
        assert!(result.is_ok(), "Conflict resolution should succeed");

        if let Ok(resolution) = result {
            assert!(
                resolution.operations.contains_key(&100),
                "Should resolve RID 100"
            );

            if let Some(OperationResolution::UseOperation(op)) = resolution.operations.get(&100) {
                assert!(
                    matches!(op.operation, Operation::Delete(100)),
                    "Should use Delete operation (later timestamp)"
                );
            } else {
                panic!("Expected UseOperation resolution");
            }
        }
    }

    #[test]
    fn test_last_write_wins_resolver_insert_wins_over_delete() {
        // Insert has later timestamp, so insert should win
        let insert_op = {
            let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
            op.timestamp = 3000; // Later timestamp
            op
        };

        let delete_op = {
            let mut op = TableOperation::new(Operation::Delete(100));
            op.timestamp = 1000; // Earlier timestamp
            op
        };

        let conflict = Conflict::InsertDeleteConflict {
            rid: 100,
            insert_op,
            delete_op,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]).unwrap();

        if let Some(OperationResolution::UseOperation(op)) = result.operations.get(&100) {
            assert!(
                matches!(op.operation, Operation::Insert(100, _)),
                "Should use Insert operation (later timestamp)"
            );
        } else {
            panic!("Expected UseOperation resolution");
        }
    }

    #[test]
    fn test_last_write_wins_resolver_insert_delete_equal_timestamps() {
        // Equal timestamps - insert should win (>= comparison favors insert)
        let insert_op = {
            let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
            op.timestamp = 1000;
            op
        };

        let delete_op = {
            let mut op = TableOperation::new(Operation::Delete(100));
            op.timestamp = 1000; // Same timestamp
            op
        };

        let conflict = Conflict::InsertDeleteConflict {
            rid: 100,
            insert_op,
            delete_op,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]).unwrap();

        if let Some(OperationResolution::UseOperation(op)) = result.operations.get(&100) {
            // With >= comparison, insert wins on ties
            assert!(
                matches!(op.operation, Operation::Insert(100, _)),
                "Insert should win on equal timestamps"
            );
        } else {
            panic!("Expected UseOperation resolution");
        }
    }

    #[test]
    fn test_last_write_wins_resolver_empty_conflict_vector() {
        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[]);
        assert!(result.is_ok());

        let resolution = result.unwrap();
        assert!(
            resolution.operations.is_empty(),
            "Empty conflicts should produce empty resolution"
        );
    }

    #[test]
    fn test_last_write_wins_resolver_multiple_conflicts() {
        // Multiple conflicts for different RIDs
        let conflict1 = Conflict::MultipleOperationsOnRid {
            rid: 10,
            operations: vec![{
                let mut op = TableOperation::new(Operation::Delete(10));
                op.timestamp = 1000;
                op
            }],
        };

        let conflict2 = Conflict::InsertDeleteConflict {
            rid: 20,
            insert_op: {
                let mut op = TableOperation::new(Operation::Insert(20, create_test_row()));
                op.timestamp = 2000;
                op
            },
            delete_op: {
                let mut op = TableOperation::new(Operation::Delete(20));
                op.timestamp = 1000;
                op
            },
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict1, conflict2]).unwrap();

        // Both RIDs should be resolved
        assert!(result.operations.contains_key(&10));
        assert!(result.operations.contains_key(&20));

        // RID 10: Delete (only operation)
        if let Some(OperationResolution::UseOperation(op)) = result.operations.get(&10) {
            assert!(matches!(op.operation, Operation::Delete(10)));
        }

        // RID 20: Insert wins (later timestamp)
        if let Some(OperationResolution::UseOperation(op)) = result.operations.get(&20) {
            assert!(matches!(op.operation, Operation::Insert(20, _)));
        }
    }

    #[test]
    fn test_resolution_default() {
        let resolution = Resolution::default();
        assert!(resolution.operations.is_empty());
    }

    #[test]
    fn test_operation_resolution_variants() {
        let row_data = create_test_row();

        // UseOperation variant
        let use_op = OperationResolution::UseOperation(TableOperation::new(Operation::Delete(1)));
        assert!(matches!(use_op, OperationResolution::UseOperation(_)));

        // UseLatest variant
        let use_latest = OperationResolution::UseLatest;
        assert!(matches!(use_latest, OperationResolution::UseLatest));

        // Merge variant
        let merge = OperationResolution::Merge(vec![
            TableOperation::new(Operation::Insert(1, row_data.clone())),
            TableOperation::new(Operation::Update(1, row_data)),
        ]);
        if let OperationResolution::Merge(ops) = merge {
            assert_eq!(ops.len(), 2);
        }

        // Reject variant
        let reject = OperationResolution::Reject("Conflict cannot be resolved".to_string());
        if let OperationResolution::Reject(msg) = reject {
            assert_eq!(msg, "Conflict cannot be resolved");
        }
    }

    #[test]
    fn test_insert_delete_conflict_validation_invalid_insert_op() {
        // insert_op is actually a Delete - should fail validation
        let insert_op = {
            let mut op = TableOperation::new(Operation::Delete(100));
            op.timestamp = 1000;
            op
        };

        let delete_op = {
            let mut op = TableOperation::new(Operation::Delete(100));
            op.timestamp = 2000;
            op
        };

        let conflict = Conflict::InsertDeleteConflict {
            rid: 100,
            insert_op,
            delete_op,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]);
        assert!(result.is_err(), "Should fail when insert_op is not Insert");

        let err = result.unwrap_err();
        assert!(
            err.to_string()
                .contains("insert_op is not an Insert operation"),
            "Error message should indicate invalid insert_op"
        );
    }

    #[test]
    fn test_insert_delete_conflict_validation_invalid_delete_op() {
        // delete_op is actually an Insert - should fail validation
        let insert_op = {
            let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
            op.timestamp = 1000;
            op
        };

        let delete_op = {
            let mut op = TableOperation::new(Operation::Insert(100, create_test_row()));
            op.timestamp = 2000;
            op
        };

        let conflict = Conflict::InsertDeleteConflict {
            rid: 100,
            insert_op,
            delete_op,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]);
        assert!(result.is_err(), "Should fail when delete_op is not Delete");

        let err = result.unwrap_err();
        assert!(
            err.to_string()
                .contains("delete_op is not a Delete operation"),
            "Error message should indicate invalid delete_op"
        );
    }

    #[test]
    fn test_insert_delete_conflict_validation_update_operations() {
        // Both operations are Update - should fail on insert_op validation first
        let insert_op = {
            let mut op = TableOperation::new(Operation::Update(100, create_test_row()));
            op.timestamp = 1000;
            op
        };

        let delete_op = {
            let mut op = TableOperation::new(Operation::Update(100, create_test_row()));
            op.timestamp = 2000;
            op
        };

        let conflict = Conflict::InsertDeleteConflict {
            rid: 100,
            insert_op,
            delete_op,
        };

        let resolver = LastWriteWinsResolver;
        let result = resolver.resolve_conflict(&[conflict]);
        assert!(
            result.is_err(),
            "Should fail when operations are not correct types"
        );

        // Should fail on insert_op validation first
        let err = result.unwrap_err();
        assert!(
            err.to_string()
                .contains("insert_op is not an Insert operation"),
            "Error should indicate insert_op validation failed first"
        );
    }
}