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
//! MethodSemanticsBuilder for creating method semantic relationship metadata entries.
//!
//! This module provides [`crate::metadata::tables::methodsemantics::MethodSemanticsBuilder`] for creating MethodSemantics table entries
//! with a fluent API. Method semantic relationships define which concrete methods provide
//! semantic behavior for properties (getters/setters) and events (add/remove/fire handlers),
//! enabling the .NET runtime to understand accessor patterns and event handling mechanisms.

use crate::{
    cilassembly::{ChangeRefRc, CilAssembly},
    metadata::{
        tables::{CodedIndex, CodedIndexType, MethodSemanticsRaw, TableDataOwned, TableId},
        token::Token,
    },
    Error, Result,
};

/// Represents the association target for a method semantic entry.
///
/// This enum captures both the row index (which can be a placeholder or actual row ID)
/// and the target table type. The `CodedIndex` is constructed at write time, not at
/// builder time, to ensure proper placeholder resolution.
#[derive(Debug, Clone, Copy)]
enum AssociationTarget {
    /// Association to a Property table entry
    Property(u32),
    /// Association to an Event table entry
    Event(u32),
}

/// Builder for creating MethodSemantics metadata entries.
///
/// `MethodSemanticsBuilder` provides a fluent API for creating MethodSemantics table entries
/// with validation and automatic relationship management. Method semantic relationships are
/// essential for connecting properties and events to their associated accessor methods,
/// enabling proper encapsulation and event handling in .NET programming models.
///
/// # Method Semantics Model
///
/// .NET method semantics follow this pattern:
/// - **Semantic Type**: The role the method plays (getter, setter, adder, etc.)
/// - **Method**: The concrete method that implements the semantic behavior
/// - **Association**: The property or event that the method provides behavior for
/// - **Runtime Integration**: The .NET runtime uses these relationships for proper dispatch
///
/// # Semantic Relationship Categories
///
/// Different categories of semantic relationships serve various purposes:
/// - **Property Semantics**: Getters, setters, and other property-related methods
/// - **Event Semantics**: Add, remove, fire, and other event-related methods
/// - **Custom Semantics**: Other specialized semantic relationships
/// - **Multiple Semantics**: Methods can have multiple semantic roles
///
/// # Coded Index Management
///
/// Method semantic relationships use HasSemantics coded indices:
/// - **Event References**: Links to event definitions in the Event table
/// - **Property References**: Links to property definitions in the Property table
/// - **Cross-Assembly Scenarios**: Support for semantic relationships across assembly boundaries
/// - **Type Safety**: Compile-time and runtime validation of semantic contracts
///
/// # Examples
///
/// ## Property Getter/Setter Relationship
///
/// ```rust,no_run
/// use dotscope::prelude::*;
///
/// # fn example(assembly: &mut CilAssembly) -> Result<()> {
/// // Create getter semantic relationship
/// let getter_semantic = MethodSemanticsBuilder::new()
///     .semantics(MethodSemanticsAttributes::GETTER)
///     .method(1) // MethodDef row index
///     .association_from_property(1) // Property row index
///     .build(assembly)?;
///
/// // Create setter semantic relationship
/// let setter_semantic = MethodSemanticsBuilder::new()
///     .semantics(MethodSemanticsAttributes::SETTER)
///     .method(2) // MethodDef row index
///     .association_from_property(1) // Same property
///     .build(assembly)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Event Add/Remove Relationship
///
/// ```rust,no_run
/// use dotscope::prelude::*;
///
/// # fn example(assembly: &mut CilAssembly) -> Result<()> {
/// // Create event add handler relationship
/// let add_semantic = MethodSemanticsBuilder::new()
///     .semantics(MethodSemanticsAttributes::ADD_ON)
///     .method(3) // Add method row index
///     .association_from_event(1) // Event row index
///     .build(assembly)?;
///
/// // Create event remove handler relationship
/// let remove_semantic = MethodSemanticsBuilder::new()
///     .semantics(MethodSemanticsAttributes::REMOVE_ON)
///     .method(4) // Remove method row index
///     .association_from_event(1) // Same event
///     .build(assembly)?;
/// # Ok(())
/// # }
/// ```
///
/// # Thread Safety
///
/// `MethodSemanticsBuilder` follows the established builder pattern:
/// - No internal state requiring synchronization
/// - Context passed to build() method handles concurrency
/// - Can be created and used across thread boundaries
/// - Final build() operation is atomic within the context
pub struct MethodSemanticsBuilder {
    /// Semantic relationship type bitmask.
    ///
    /// Defines the method's semantic role using MethodSemanticsAttributes constants.
    /// Can combine multiple semantic types using bitwise OR operations.
    semantics: Option<u32>,

    /// Method that implements the semantic behavior.
    ///
    /// Row index referencing a MethodDef entry that provides the concrete implementation
    /// for the semantic relationship. Can be a placeholder or actual row ID.
    method: Option<u32>,

    /// Association target capturing the row index and target table type.
    ///
    /// The row index can be a placeholder or actual row ID. The `CodedIndex`
    /// is constructed at write time, not at builder time.
    association: Option<AssociationTarget>,
}

impl MethodSemanticsBuilder {
    /// Creates a new `MethodSemanticsBuilder` instance.
    ///
    /// Initializes all fields to `None`, requiring explicit configuration
    /// through the fluent API methods before building.
    ///
    /// # Returns
    ///
    /// New builder instance ready for configuration.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::prelude::*;
    ///
    /// let builder = MethodSemanticsBuilder::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            semantics: None,
            method: None,
            association: None,
        }
    }

    /// Sets the semantic relationship type.
    ///
    /// Specifies the role this method plays in relation to the associated
    /// property or event using MethodSemanticsAttributes constants.
    ///
    /// # Arguments
    ///
    /// * `semantics` - Bitmask of semantic attributes (can combine multiple values)
    ///
    /// # Returns
    ///
    /// Updated builder instance for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::prelude::*;
    ///
    /// let builder = MethodSemanticsBuilder::new()
    ///     .semantics(MethodSemanticsAttributes::GETTER);
    ///
    /// // Multiple semantics can be combined
    /// let combined = MethodSemanticsBuilder::new()
    ///     .semantics(MethodSemanticsAttributes::GETTER | MethodSemanticsAttributes::OTHER);
    /// ```
    #[must_use]
    pub fn semantics(mut self, semantics: u32) -> Self {
        self.semantics = Some(semantics);
        self
    }

    /// Sets the method that implements the semantic behavior.
    ///
    /// Specifies the MethodDef row index for the method that provides the concrete
    /// implementation of the semantic relationship.
    ///
    /// # Arguments
    ///
    /// * `method` - Row index referencing a MethodDef table entry
    ///
    /// # Returns
    ///
    /// Updated builder instance for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::prelude::*;
    ///
    /// let builder = MethodSemanticsBuilder::new()
    ///     .method(1); // MethodDef row index
    /// ```
    #[must_use]
    pub fn method(mut self, method: u32) -> Self {
        self.method = Some(method);
        self
    }

    /// Sets the association to a property using its row index or placeholder.
    ///
    /// Stores the property row index for later construction of a HasSemantics coded index
    /// during the write phase. The `CodedIndex` is NOT created at builder time to ensure
    /// proper placeholder resolution.
    ///
    /// # Arguments
    ///
    /// * `property` - Row index or placeholder referencing a Property table entry
    ///
    /// # Returns
    ///
    /// Updated builder instance for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::prelude::*;
    ///
    /// let builder = MethodSemanticsBuilder::new()
    ///     .association_from_property(1); // Property row index
    /// ```
    #[must_use]
    pub fn association_from_property(mut self, property: u32) -> Self {
        self.association = Some(AssociationTarget::Property(property));
        self
    }

    /// Sets the association to an event using its row index or placeholder.
    ///
    /// Stores the event row index for later construction of a HasSemantics coded index
    /// during the write phase. The `CodedIndex` is NOT created at builder time to ensure
    /// proper placeholder resolution.
    ///
    /// # Arguments
    ///
    /// * `event` - Row index or placeholder referencing an Event table entry
    ///
    /// # Returns
    ///
    /// Updated builder instance for method chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::prelude::*;
    ///
    /// let builder = MethodSemanticsBuilder::new()
    ///     .association_from_event(1); // Event row index
    /// ```
    #[must_use]
    pub fn association_from_event(mut self, event: u32) -> Self {
        self.association = Some(AssociationTarget::Event(event));
        self
    }

    /// Builds the MethodSemantics entry and adds it to the assembly.
    ///
    /// Validates all required fields, creates the raw MethodSemantics entry,
    /// and adds it to the MethodSemantics table through the builder assembly.
    /// Returns the token for the newly created entry.
    ///
    /// # Arguments
    ///
    /// * `assembly` - Mutable reference to the CilAssembly for assembly modification
    ///
    /// # Returns
    ///
    /// `Result<Token>` - Token for the created MethodSemantics entry or error if validation fails
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Required semantics field is not set
    /// - Required method field is not set  
    /// - Required association field is not set
    /// - Context operations fail (heap allocation, table modification)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::prelude::*;
    ///
    /// # fn example(assembly: &mut CilAssembly) -> Result<()> {
    /// let semantic_ref = MethodSemanticsBuilder::new()
    ///     .semantics(MethodSemanticsAttributes::GETTER)
    ///     .method(1)
    ///     .association_from_property(1)
    ///     .build(assembly)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self, assembly: &mut CilAssembly) -> Result<ChangeRefRc> {
        // Validate required fields
        let semantics = self.semantics.ok_or_else(|| {
            Error::ModificationInvalid("MethodSemantics semantics field is required".to_string())
        })?;

        let method = self.method.ok_or_else(|| {
            Error::ModificationInvalid("MethodSemantics method field is required".to_string())
        })?;

        let association_target = self.association.ok_or_else(|| {
            Error::ModificationInvalid("MethodSemantics association field is required".to_string())
        })?;

        // Construct the CodedIndex from the stored target information.
        // The row value may be a placeholder that will be resolved at write time
        // by the ResolvePlaceholders implementation.
        let association = match association_target {
            AssociationTarget::Property(row) => {
                CodedIndex::new(TableId::Property, row, CodedIndexType::HasSemantics)
            }
            AssociationTarget::Event(row) => {
                CodedIndex::new(TableId::Event, row, CodedIndexType::HasSemantics)
            }
        };

        let method_semantics_raw = MethodSemanticsRaw {
            rid: 0,
            token: Token::new(0),
            offset: 0,
            semantics,
            method,
            association,
        };

        assembly.table_row_add(
            TableId::MethodSemantics,
            TableDataOwned::MethodSemantics(method_semantics_raw),
        )
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cilassembly::{ChangeRefKind, CilAssembly},
        metadata::{cilassemblyview::CilAssemblyView, tables::MethodSemanticsAttributes},
    };
    use std::{env, path::PathBuf};

    #[test]
    fn test_methodsemantics_builder_creation() {
        let builder = MethodSemanticsBuilder::new();
        assert!(builder.semantics.is_none());
        assert!(builder.method.is_none());
        assert!(builder.association.is_none());
    }

    #[test]
    fn test_methodsemantics_builder_default() {
        let builder = MethodSemanticsBuilder::default();
        assert!(builder.semantics.is_none());
        assert!(builder.method.is_none());
        assert!(builder.association.is_none());
    }

    #[test]
    fn test_property_getter_semantic() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::GETTER)
                .method(1)
                .association_from_property(1)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_property_setter_semantic() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::SETTER)
                .method(2)
                .association_from_property(1)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_event_add_semantic() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::ADD_ON)
                .method(3)
                .association_from_event(1)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_event_remove_semantic() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::REMOVE_ON)
                .method(4)
                .association_from_event(1)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_event_fire_semantic() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::FIRE)
                .method(5)
                .association_from_event(1)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_combined_semantics() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::GETTER | MethodSemanticsAttributes::OTHER)
                .method(6)
                .association_from_property(2)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_association_with_row_index() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Test using direct row index (not a placeholder)
            let semantic_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::GETTER)
                .method(7)
                .association_from_property(1)
                .build(&mut assembly)?;

            assert_eq!(
                semantic_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
        }
        Ok(())
    }

    #[test]
    fn test_multiple_method_semantics() -> Result<()> {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Create multiple semantic relationships for the same property
            let getter_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::GETTER)
                .method(1)
                .association_from_property(1)
                .build(&mut assembly)?;

            let setter_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::SETTER)
                .method(2)
                .association_from_property(1)
                .build(&mut assembly)?;

            let other_ref = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::OTHER)
                .method(3)
                .association_from_property(1)
                .build(&mut assembly)?;

            assert_eq!(
                getter_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
            assert_eq!(
                setter_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
            assert_eq!(
                other_ref.kind(),
                ChangeRefKind::TableRow(TableId::MethodSemantics)
            );
            assert!(!std::sync::Arc::ptr_eq(&getter_ref, &setter_ref));
            assert!(!std::sync::Arc::ptr_eq(&setter_ref, &other_ref));
        }
        Ok(())
    }

    #[test]
    fn test_build_without_semantics_fails() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let result = MethodSemanticsBuilder::new()
                .method(1)
                .association_from_property(1)
                .build(&mut assembly);

            assert!(result.is_err());
            assert!(result
                .unwrap_err()
                .to_string()
                .contains("semantics field is required"));
        }
    }

    #[test]
    fn test_build_without_method_fails() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let result = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::GETTER)
                .association_from_property(1)
                .build(&mut assembly);

            assert!(result.is_err());
            assert!(result
                .unwrap_err()
                .to_string()
                .contains("method field is required"));
        }
    }

    #[test]
    fn test_build_without_association_fails() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let result = MethodSemanticsBuilder::new()
                .semantics(MethodSemanticsAttributes::GETTER)
                .method(1)
                .build(&mut assembly);

            assert!(result.is_err());
            assert!(result
                .unwrap_err()
                .to_string()
                .contains("association field is required"));
        }
    }
}