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
//! Method argument storage for CIL emulation.
//!
//! This module provides [`ArgumentStorage`] for managing method arguments during
//! CIL bytecode execution. Arguments are the values passed to a method call by
//! the caller and are accessible via `ldarg`, `starg`, and related instructions.
//!
//! # CIL Argument Semantics
//!
//! Unlike local variables, arguments are initialized by the caller before method
//! entry. For instance methods, argument 0 is implicitly the `this` reference.
//!
//! # Type Safety
//!
//! Argument storage tracks both values and their declared CIL types. The [`set`](ArgumentStorage::set)
//! method performs type checking using [`CilFlavor`](crate::metadata::typesystem::CilFlavor)
//! compatibility rules, with relaxed checking for symbolic values used in analysis.

use std::fmt;

use crate::{
    emulation::{engine::EmulationError, EmValue},
    metadata::typesystem::CilFlavor,
    Result,
};

/// Storage for method arguments.
///
/// Arguments are passed to a method by the caller and can be read or modified
/// during method execution. For instance methods, argument 0 is typically `this`.
///
/// # Example
///
/// ```rust
/// use dotscope::emulation::{ArgumentStorage, EmValue};
/// use dotscope::metadata::typesystem::CilFlavor;
///
/// // Create arguments from caller's values
/// let mut args = ArgumentStorage::new(
///     vec![EmValue::I32(10), EmValue::I32(20)],
///     vec![CilFlavor::I4, CilFlavor::I4],
/// );
///
/// // Access arguments
/// assert_eq!(args.get(0).unwrap(), &EmValue::I32(10));
/// assert_eq!(args.get(1).unwrap(), &EmValue::I32(20));
///
/// // Modify argument (for ref/out parameters)
/// args.set(0, EmValue::I32(42)).unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct ArgumentStorage {
    /// The argument values.
    values: Vec<EmValue>,

    /// The declared types for each argument.
    types: Vec<CilFlavor>,

    /// Whether this is an instance method (arg 0 is 'this').
    has_this: bool,
}

impl ArgumentStorage {
    /// Creates argument storage from caller values and types.
    ///
    /// # Arguments
    ///
    /// * `values` - Values passed by the caller
    /// * `types` - CIL type flavors for each argument
    ///
    /// # Panics
    ///
    /// Panics if values and types have different lengths.
    #[must_use]
    pub fn new(values: Vec<EmValue>, types: Vec<CilFlavor>) -> Self {
        assert_eq!(
            values.len(),
            types.len(),
            "values and types must have same length"
        );
        ArgumentStorage {
            values,
            types,
            has_this: false,
        }
    }

    /// Creates argument storage for an instance method.
    ///
    /// Argument 0 will be the `this` reference.
    ///
    /// # Arguments
    ///
    /// * `this_ref` - The 'this' object reference
    /// * `arg_values` - Additional argument values
    /// * `arg_types` - CIL type flavors for additional arguments
    #[must_use]
    pub fn with_this(
        this_ref: EmValue,
        arg_values: Vec<EmValue>,
        arg_types: Vec<CilFlavor>,
    ) -> Self {
        let mut values = vec![this_ref];
        values.extend(arg_values);

        let mut types = vec![CilFlavor::Object];
        types.extend(arg_types);

        ArgumentStorage {
            values,
            types,
            has_this: true,
        }
    }

    /// Creates empty argument storage.
    #[must_use]
    pub fn empty() -> Self {
        ArgumentStorage {
            values: Vec::new(),
            types: Vec::new(),
            has_this: false,
        }
    }

    /// Gets the value of an argument.
    ///
    /// # Arguments
    ///
    /// * `index` - The argument index (0-based)
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::ArgumentIndexOutOfBounds`] if index is out of bounds.
    pub fn get(&self, index: usize) -> Result<&EmValue> {
        if index >= self.values.len() {
            return Err(EmulationError::ArgumentIndexOutOfBounds {
                index,
                count: self.values.len(),
            }
            .into());
        }
        Ok(&self.values[index])
    }

    /// Gets a mutable reference to an argument.
    ///
    /// # Arguments
    ///
    /// * `index` - The argument index (0-based)
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::ArgumentIndexOutOfBounds`] if index is out of bounds.
    pub fn get_mut(&mut self, index: usize) -> Result<&mut EmValue> {
        if index >= self.values.len() {
            return Err(EmulationError::ArgumentIndexOutOfBounds {
                index,
                count: self.values.len(),
            }
            .into());
        }
        Ok(&mut self.values[index])
    }

    /// Sets the value of an argument.
    ///
    /// This is used for ref/out parameters that can be modified.
    ///
    /// # Arguments
    ///
    /// * `index` - The argument index (0-based)
    /// * `value` - The new value
    ///
    /// # Errors
    ///
    /// Returns error if index is out of bounds or type mismatches.
    pub fn set(&mut self, index: usize, value: EmValue) -> Result<()> {
        if index >= self.values.len() {
            return Err(EmulationError::ArgumentIndexOutOfBounds {
                index,
                count: self.values.len(),
            }
            .into());
        }

        // Type check (relaxed for compatible types and symbolic values)
        let expected = &self.types[index];
        let found = value.cil_flavor();

        // Check type compatibility using CilFlavor's stack compatibility rules
        if !expected.is_stack_assignable_from(&found) && !value.is_symbolic() {
            return Err(EmulationError::ArgumentFlavorMismatch {
                index,
                expected: Box::new(expected.clone()),
                found: Box::new(found),
            }
            .into());
        }

        self.values[index] = value;
        Ok(())
    }

    /// Gets the type of an argument.
    ///
    /// # Arguments
    ///
    /// * `index` - The argument index (0-based)
    ///
    /// # Errors
    ///
    /// Returns error if index is out of bounds.
    pub fn get_type(&self, index: usize) -> Result<&CilFlavor> {
        if index >= self.types.len() {
            return Err(EmulationError::ArgumentIndexOutOfBounds {
                index,
                count: self.types.len(),
            }
            .into());
        }
        Ok(&self.types[index])
    }

    /// Gets the `this` reference for instance methods.
    ///
    /// # Returns
    ///
    /// `Some(&EmValue)` if this is an instance method, `None` otherwise.
    #[must_use]
    pub fn this(&self) -> Option<&EmValue> {
        if self.has_this && !self.values.is_empty() {
            Some(&self.values[0])
        } else {
            None
        }
    }

    /// Returns `true` if this is an instance method.
    #[must_use]
    pub fn has_this(&self) -> bool {
        self.has_this
    }

    /// Returns the number of arguments.
    #[must_use]
    pub fn count(&self) -> usize {
        self.values.len()
    }

    /// Returns `true` if there are no arguments.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Returns a slice of all argument values.
    #[must_use]
    pub fn values(&self) -> &[EmValue] {
        &self.values
    }

    /// Returns a slice of all argument types.
    #[must_use]
    pub fn types(&self) -> &[CilFlavor] {
        &self.types
    }

    /// Returns an iterator over (index, value) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (usize, &EmValue)> {
        self.values.iter().enumerate()
    }

    /// Creates a snapshot of the current argument state.
    #[must_use]
    pub fn snapshot(&self) -> Vec<EmValue> {
        self.values.clone()
    }

    /// Restores arguments from a previous snapshot.
    ///
    /// # Panics
    ///
    /// Panics if snapshot length doesn't match argument count.
    pub fn restore(&mut self, snapshot: Vec<EmValue>) {
        assert_eq!(snapshot.len(), self.values.len(), "snapshot size mismatch");
        self.values = snapshot;
    }
}

impl Default for ArgumentStorage {
    fn default() -> Self {
        Self::empty()
    }
}

impl fmt::Display for ArgumentStorage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Args[")?;
        for (i, (value, typ)) in self.values.iter().zip(self.types.iter()).enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            if i == 0 && self.has_this {
                write!(f, "this={value}")?;
            } else {
                write!(f, "{i}:{typ:?}={value}")?;
            }
        }
        write!(f, "]")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{emulation::HeapRef, Error};

    #[test]
    fn test_arguments_creation() {
        let args = ArgumentStorage::new(
            vec![EmValue::I32(10), EmValue::I32(20)],
            vec![CilFlavor::I4, CilFlavor::I4],
        );

        assert_eq!(args.count(), 2);
        assert_eq!(args.get(0).unwrap(), &EmValue::I32(10));
        assert_eq!(args.get(1).unwrap(), &EmValue::I32(20));
        assert!(!args.has_this());
    }

    #[test]
    fn test_arguments_with_this() {
        let this_ref = EmValue::ObjectRef(HeapRef::new(1));
        let args = ArgumentStorage::with_this(
            this_ref.clone(),
            vec![EmValue::I32(42)],
            vec![CilFlavor::I4],
        );

        assert!(args.has_this());
        assert_eq!(args.count(), 2);
        assert_eq!(args.this().unwrap(), &this_ref);
        assert_eq!(args.get(1).unwrap(), &EmValue::I32(42));
    }

    #[test]
    fn test_arguments_empty() {
        let args = ArgumentStorage::empty();
        assert!(args.is_empty());
        assert!(!args.has_this());
    }

    #[test]
    fn test_arguments_get_set() {
        let mut args = ArgumentStorage::new(vec![EmValue::I32(10)], vec![CilFlavor::I4]);

        args.set(0, EmValue::I32(42)).unwrap();
        assert_eq!(args.get(0).unwrap(), &EmValue::I32(42));
    }

    #[test]
    fn test_arguments_out_of_bounds() {
        let args = ArgumentStorage::new(vec![EmValue::I32(10)], vec![CilFlavor::I4]);

        assert!(matches!(
            args.get(5),
            Err(Error::Emulation(ref e)) if matches!(e.as_ref(), EmulationError::ArgumentIndexOutOfBounds { .. })
        ));
    }

    #[test]
    fn test_arguments_type_mismatch() {
        let mut args = ArgumentStorage::new(vec![EmValue::I32(10)], vec![CilFlavor::I4]);

        let result = args.set(0, EmValue::I64(100));
        assert!(matches!(
            result,
            Err(Error::Emulation(ref e)) if matches!(e.as_ref(), EmulationError::ArgumentFlavorMismatch { .. })
        ));
    }

    #[test]
    fn test_arguments_get_type() {
        let args = ArgumentStorage::new(
            vec![EmValue::I32(10), EmValue::I64(20)],
            vec![CilFlavor::I4, CilFlavor::I8],
        );

        assert_eq!(args.get_type(0).unwrap(), &CilFlavor::I4);
        assert_eq!(args.get_type(1).unwrap(), &CilFlavor::I8);
    }

    #[test]
    fn test_arguments_snapshot_restore() {
        let mut args = ArgumentStorage::new(vec![EmValue::I32(10)], vec![CilFlavor::I4]);

        let snapshot = args.snapshot();
        args.set(0, EmValue::I32(99)).unwrap();

        args.restore(snapshot);
        assert_eq!(args.get(0).unwrap(), &EmValue::I32(10));
    }

    #[test]
    fn test_arguments_iter() {
        let args = ArgumentStorage::new(
            vec![EmValue::I32(10), EmValue::I32(20)],
            vec![CilFlavor::I4, CilFlavor::I4],
        );

        let items: Vec<_> = args.iter().collect();
        assert_eq!(items.len(), 2);
    }

    #[test]
    fn test_arguments_display() {
        let args = ArgumentStorage::new(vec![EmValue::I32(42)], vec![CilFlavor::I4]);

        let display = format!("{args}");
        assert!(display.contains("42"));
    }
}