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
//! Parameter builders for creating mock Param instances for method testing
//!
//! This module provides builders for creating Param instances with various
//! characteristics including input/output parameters, defaults, and marshalling.

use std::sync::{atomic::AtomicBool, Arc, OnceLock};

use crate::{
    metadata::{
        marshalling::MarshallingInfo,
        tables::{Param, ParamRc},
        token::Token,
        typesystem::{
            CilFlavor, CilPrimitive, CilTypeRef, CompleteTypeSpec, TypeRegistry, TypeSource,
        },
    },
    prelude::{CilPrimitiveData, CilPrimitiveKind, ParamAttributes},
    test::{builders::FieldBuilder, factories::metadata::customattributes::get_test_type_registry},
};

/// Parameter attribute flags for various parameter characteristics
#[derive(Debug, Clone, Copy)]
pub enum ParamDirection {
    /// Input parameter (default)
    In,
    /// Output parameter
    Out,
    /// Input/output parameter
    InOut,
}

/// Parameter default value types
#[derive(Debug, Clone)]
pub enum ParamDefault {
    /// Boolean default
    Bool(bool),
    /// 8-bit signed integer
    I1(i8),
    /// 8-bit unsigned integer
    U1(u8),
    /// 16-bit signed integer
    I2(i16),
    /// 16-bit unsigned integer
    U2(u16),
    /// 32-bit signed integer
    I4(i32),
    /// 32-bit unsigned integer
    U4(u32),
    /// 64-bit signed integer
    I8(i64),
    /// 64-bit unsigned integer
    U8(u64),
    /// 32-bit floating point
    R4(f32),
    /// 64-bit floating point
    R8(f64),
    /// String default
    String(String),
    /// Null reference
    Null,
}

/// Builder for creating mock Param instances
pub struct ParamBuilder {
    rid: u32,
    sequence: u32,
    name: Option<String>,
    flags: u32,
    direction: ParamDirection,
    default_value: Option<ParamDefault>,
    marshal_info: Option<MarshallingInfo>,
    is_optional: bool,
    type_flavor: Option<CilFlavor>,
}

impl ParamBuilder {
    /// Create a new parameter builder
    pub fn new(sequence: u32, name: Option<String>) -> Self {
        Self {
            rid: sequence,
            sequence,
            name,
            flags: 0,
            direction: ParamDirection::In,
            default_value: None,
            marshal_info: None,
            is_optional: false,
            type_flavor: None,
        }
    }

    /// Create a return value parameter (sequence 0)
    pub fn return_value() -> Self {
        Self::new(0, None)
    }

    /// Create a named input parameter
    pub fn input_param(sequence: u32, name: &str) -> Self {
        Self::new(sequence, Some(name.to_string())).with_direction(ParamDirection::In)
    }

    /// Create a named output parameter
    pub fn output_param(sequence: u32, name: &str) -> Self {
        Self::new(sequence, Some(name.to_string())).with_direction(ParamDirection::Out)
    }

    /// Create an input/output parameter
    pub fn inout_param(sequence: u32, name: &str) -> Self {
        Self::new(sequence, Some(name.to_string())).with_direction(ParamDirection::InOut)
    }

    pub fn with_rid(mut self, rid: u32) -> Self {
        self.rid = rid;
        self
    }

    pub fn with_direction(mut self, direction: ParamDirection) -> Self {
        self.direction = direction;
        self
    }

    pub fn with_default_value(mut self, default: ParamDefault) -> Self {
        self.default_value = Some(default);
        self
    }

    pub fn with_marshal_info(mut self, marshal: MarshallingInfo) -> Self {
        self.marshal_info = Some(marshal);
        self
    }

    pub fn with_optional(mut self) -> Self {
        self.is_optional = true;
        self
    }

    pub fn with_flags(mut self, flags: u32) -> Self {
        self.flags = flags;
        self
    }

    /// Set the parameter type from a CilFlavor
    pub fn with_type_from_flavor(mut self, flavor: CilFlavor) -> Self {
        // Store the flavor - it will be resolved to an actual type during build()
        self.type_flavor = Some(flavor);
        self
    }

    /// Set the parameter type from a CilPrimitiveKind
    pub fn with_primitive_type(mut self, kind: CilPrimitiveKind) -> Self {
        self.type_flavor = Some(match kind {
            CilPrimitiveKind::Boolean => CilFlavor::Boolean,
            CilPrimitiveKind::Char => CilFlavor::Char,
            CilPrimitiveKind::I1 => CilFlavor::I1,
            CilPrimitiveKind::U1 => CilFlavor::U1,
            CilPrimitiveKind::I2 => CilFlavor::I2,
            CilPrimitiveKind::U2 => CilFlavor::U2,
            CilPrimitiveKind::I4 => CilFlavor::I4,
            CilPrimitiveKind::U4 => CilFlavor::U4,
            CilPrimitiveKind::I8 => CilFlavor::I8,
            CilPrimitiveKind::U8 => CilFlavor::U8,
            CilPrimitiveKind::R4 => CilFlavor::R4,
            CilPrimitiveKind::R8 => CilFlavor::R8,
            CilPrimitiveKind::I => CilFlavor::I,
            CilPrimitiveKind::U => CilFlavor::U,
            CilPrimitiveKind::String => CilFlavor::String,
            CilPrimitiveKind::Object => CilFlavor::Object,
            CilPrimitiveKind::Void => CilFlavor::Void,
            CilPrimitiveKind::Null => CilFlavor::Object, // Treat null as object reference
            CilPrimitiveKind::TypedReference => CilFlavor::Object, // Special case
            CilPrimitiveKind::ValueType => CilFlavor::ValueType,
            // Handle remaining variants - these may not have direct CilFlavor equivalents
            _ => CilFlavor::Object, // Default fallback
        });
        self
    }

    /// Build the Param instance
    ///
    /// # Arguments
    /// * `type_registry` - Optional TypeRegistry for resolving parameter types.
    ///   If None, uses a shared default test registry.
    pub fn build(self, type_registry: Option<&Arc<TypeRegistry>>) -> ParamRc {
        let mut flags = self.flags;

        // Set direction flags
        match self.direction {
            ParamDirection::In => flags |= ParamAttributes::IN,
            ParamDirection::Out => flags |= ParamAttributes::OUT,
            ParamDirection::InOut => {
                flags |= ParamAttributes::IN | ParamAttributes::OUT;
            }
        }

        // Set optional flag
        if self.is_optional {
            flags |= ParamAttributes::OPTIONAL;
        }

        // Set default value flag
        if self.default_value.is_some() {
            flags |= ParamAttributes::HAS_DEFAULT;
        }

        // Set marshal flag
        if self.marshal_info.is_some() {
            flags |= ParamAttributes::HAS_FIELD_MARSHAL;
        }

        let param = Arc::new(Param {
            rid: self.rid,
            token: Token::new(0x08000000 + self.rid),
            offset: 0,
            flags,
            sequence: self.sequence,
            name: self.name,
            default: OnceLock::new(),
            marshal: OnceLock::new(),
            modifiers: Arc::new(boxcar::Vec::new()),
            base: OnceLock::new(),
            is_by_ref: AtomicBool::new(false),
            custom_attributes: Arc::new(boxcar::Vec::new()),
        });

        // Set default value if provided
        if let Some(default) = self.default_value {
            let primitive = match default {
                ParamDefault::Bool(v) => CilPrimitive {
                    kind: CilPrimitiveKind::Boolean,
                    data: CilPrimitiveData::Boolean(v),
                },
                ParamDefault::I1(v) => CilPrimitive {
                    kind: CilPrimitiveKind::I1,
                    data: CilPrimitiveData::I1(v),
                },
                ParamDefault::U1(v) => CilPrimitive {
                    kind: CilPrimitiveKind::U1,
                    data: CilPrimitiveData::U1(v),
                },
                ParamDefault::I2(v) => CilPrimitive {
                    kind: CilPrimitiveKind::I2,
                    data: CilPrimitiveData::I2(v),
                },
                ParamDefault::U2(v) => CilPrimitive {
                    kind: CilPrimitiveKind::U2,
                    data: CilPrimitiveData::U2(v),
                },
                ParamDefault::I4(v) => CilPrimitive {
                    kind: CilPrimitiveKind::I4,
                    data: CilPrimitiveData::I4(v),
                },
                ParamDefault::U4(v) => CilPrimitive {
                    kind: CilPrimitiveKind::U4,
                    data: CilPrimitiveData::U4(v),
                },
                ParamDefault::I8(v) => CilPrimitive {
                    kind: CilPrimitiveKind::I8,
                    data: CilPrimitiveData::I8(v),
                },
                ParamDefault::U8(v) => CilPrimitive {
                    kind: CilPrimitiveKind::U8,
                    data: CilPrimitiveData::U8(v),
                },
                ParamDefault::R4(v) => CilPrimitive {
                    kind: CilPrimitiveKind::R4,
                    data: CilPrimitiveData::R4(v),
                },
                ParamDefault::R8(v) => CilPrimitive {
                    kind: CilPrimitiveKind::R8,
                    data: CilPrimitiveData::R8(v),
                },
                ParamDefault::String(v) => CilPrimitive {
                    kind: CilPrimitiveKind::String,
                    data: CilPrimitiveData::String(v),
                },
                ParamDefault::Null => CilPrimitive {
                    kind: CilPrimitiveKind::Class,
                    data: CilPrimitiveData::None,
                },
            };
            let _ = param.default.set(primitive);
        }

        // Set marshal info if provided
        if let Some(marshal) = self.marshal_info {
            let _ = param.marshal.set(marshal);
        }

        // Set parameter type if provided
        if let Some(flavor) = self.type_flavor {
            // Use provided registry or get the shared test registry for backwards compatibility
            let registry = type_registry
                .cloned()
                .unwrap_or_else(get_test_type_registry);

            let param_type = match flavor {
                CilFlavor::Boolean => registry.get_primitive(CilPrimitiveKind::Boolean).unwrap(),
                CilFlavor::Char => registry.get_primitive(CilPrimitiveKind::Char).unwrap(),
                CilFlavor::I1 => registry.get_primitive(CilPrimitiveKind::I1).unwrap(),
                CilFlavor::U1 => registry.get_primitive(CilPrimitiveKind::U1).unwrap(),
                CilFlavor::I2 => registry.get_primitive(CilPrimitiveKind::I2).unwrap(),
                CilFlavor::U2 => registry.get_primitive(CilPrimitiveKind::U2).unwrap(),
                CilFlavor::I4 => registry.get_primitive(CilPrimitiveKind::I4).unwrap(),
                CilFlavor::U4 => registry.get_primitive(CilPrimitiveKind::U4).unwrap(),
                CilFlavor::I8 => registry.get_primitive(CilPrimitiveKind::I8).unwrap(),
                CilFlavor::U8 => registry.get_primitive(CilPrimitiveKind::U8).unwrap(),
                CilFlavor::R4 => registry.get_primitive(CilPrimitiveKind::R4).unwrap(),
                CilFlavor::R8 => registry.get_primitive(CilPrimitiveKind::R8).unwrap(),
                CilFlavor::I => registry.get_primitive(CilPrimitiveKind::I).unwrap(),
                CilFlavor::U => registry.get_primitive(CilPrimitiveKind::U).unwrap(),
                CilFlavor::String => registry.get_primitive(CilPrimitiveKind::String).unwrap(),
                CilFlavor::Object => registry.get_primitive(CilPrimitiveKind::Object).unwrap(),
                CilFlavor::Void => registry.get_primitive(CilPrimitiveKind::Void).unwrap(),
                CilFlavor::Class => {
                    // For Class flavor, use System.Type (the most common Class parameter type)
                    // This is correct because custom attributes typically use System.Type parameters
                    registry
                        .get_or_create_type(&CompleteTypeSpec {
                            token_init: None,
                            flavor: CilFlavor::Class,
                            namespace: "System".to_string(),
                            name: "Type".to_string(),
                            source: TypeSource::Unknown,
                            generic_args: None,
                            base_type: None,
                            flags: None,
                        })
                        .unwrap()
                }
                CilFlavor::ValueType => {
                    // For ValueType flavor in tests, create an enum type
                    // Use a unique name to avoid conflicts with Class flavor tests
                    // First get System.Enum as the base type
                    let enum_base = registry
                        .get_or_create_type(&CompleteTypeSpec {
                            token_init: None,
                            flavor: CilFlavor::Class,
                            namespace: "System".to_string(),
                            name: "Enum".to_string(),
                            source: TypeSource::Unknown,
                            generic_args: None,
                            base_type: None,
                            flags: None,
                        })
                        .unwrap();

                    // Get System.Int32 as the underlying type for the value__ field
                    let int32_type = registry.get_primitive(CilPrimitiveKind::I4).unwrap();

                    // Create test enum type that inherits from System.Enum
                    // Use TestEnum instead of TestType to avoid collision with Class flavor
                    let test_enum = registry
                        .get_or_create_type(&CompleteTypeSpec {
                            token_init: None,
                            flavor: CilFlavor::ValueType,
                            namespace: "System".to_string(),
                            name: "TestEnum".to_string(),
                            source: TypeSource::Unknown,
                            generic_args: None,
                            base_type: Some(enum_base),
                            flags: None,
                        })
                        .unwrap();

                    // Add required value__ field for enum types (ECMA-335 requirement)
                    let value_field = FieldBuilder::new("value__", int32_type).build();

                    // Add the value__ field to the enum type
                    test_enum.fields.push(value_field);

                    test_enum
                }
                other_flavor => registry
                    .get_or_create_type(&CompleteTypeSpec {
                        token_init: None,
                        flavor: other_flavor,
                        namespace: "System".to_string(),
                        name: "TestType".to_string(),
                        source: TypeSource::Unknown,
                        generic_args: None,
                        base_type: None,
                        flags: None,
                    })
                    .unwrap(),
            };

            let _ = param.base.set(CilTypeRef::from(param_type));
        }

        param
    }
}

impl Default for ParamBuilder {
    fn default() -> Self {
        Self::new(1, Some("param".to_string()))
    }
}

/// Helper builder for creating parameter lists for methods
pub struct ParamListBuilder {
    params: Vec<ParamBuilder>,
    include_return_param: bool,
}

impl ParamListBuilder {
    pub fn new() -> Self {
        Self {
            params: Vec::new(),
            include_return_param: false,
        }
    }

    /// Include a return value parameter (sequence 0)
    pub fn with_return_param(mut self) -> Self {
        self.include_return_param = true;
        self
    }

    /// Add a parameter to the list
    pub fn add_param(mut self, param: ParamBuilder) -> Self {
        self.params.push(param);
        self
    }

    /// Add an input parameter with the given name
    pub fn add_input_param(mut self, name: &str) -> Self {
        let sequence = self.params.len() as u32 + 1;
        self.params.push(ParamBuilder::input_param(sequence, name));
        self
    }

    /// Add an output parameter with the given name
    pub fn add_output_param(mut self, name: &str) -> Self {
        let sequence = self.params.len() as u32 + 1;
        self.params.push(ParamBuilder::output_param(sequence, name));
        self
    }

    /// Build the parameter list
    pub fn build(self, type_registry: Option<&Arc<TypeRegistry>>) -> Arc<boxcar::Vec<ParamRc>> {
        let params = Arc::new(boxcar::Vec::new());

        // Add return parameter if requested
        if self.include_return_param {
            params.push(ParamBuilder::return_value().build(type_registry));
        }

        // Add all other parameters
        for param_builder in self.params {
            params.push(param_builder.build(type_registry));
        }

        params
    }
}

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