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
//! Local variable storage for CIL emulation.
//!
//! This module provides [`LocalVariables`] for managing method-local storage
//! during CIL bytecode execution. Local variables are declared in the method's
//! local signature and are accessible via `ldloc`, `stloc`, and related instructions.
//!
//! # CIL Local Variable Semantics
//!
//! Local variables provide method-scoped storage slots that persist for the
//! duration of a method call. Each local has a declared type and is initialized
//! to its default value (zero, null, or default struct) at method entry.
//!
//! # Type Safety
//!
//! Local variable storage tracks both values and their declared CIL types.
//! The [`set`](LocalVariables::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 local variables.
///
/// Local variables are defined by the method metadata and persist for the
/// duration of the method call. They are initialized to default values
/// based on their type.
///
/// # Example
///
/// ```rust
/// use dotscope::emulation::{EmValue, LocalVariables};
/// use dotscope::metadata::typesystem::CilFlavor;
///
/// // Create locals from type information
/// let mut locals = LocalVariables::new(vec![
///     CilFlavor::I4,
///     CilFlavor::I8,
///     CilFlavor::Object,
/// ]);
///
/// // Load default values
/// assert_eq!(locals.get(0).unwrap(), &EmValue::I32(0));
/// assert_eq!(locals.get(2).unwrap(), &EmValue::Null);
///
/// // Store and load
/// locals.set(0, EmValue::I32(42)).unwrap();
/// assert_eq!(locals.get(0).unwrap(), &EmValue::I32(42));
/// ```
#[derive(Clone, Debug)]
pub struct LocalVariables {
    /// The local variable values.
    values: Vec<EmValue>,

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

impl LocalVariables {
    /// Creates local variables from their type definitions.
    ///
    /// Each local is initialized to its default value based on type.
    ///
    /// # Arguments
    ///
    /// * `types` - CIL type flavors for each local variable
    #[must_use]
    pub fn new(types: Vec<CilFlavor>) -> Self {
        let values = types.iter().map(EmValue::default_for_flavor).collect();

        LocalVariables { values, types }
    }

    /// Creates an empty local variable storage.
    #[must_use]
    pub fn empty() -> Self {
        LocalVariables {
            values: Vec::new(),
            types: Vec::new(),
        }
    }

    /// Creates local variables with explicit initial values.
    ///
    /// # Arguments
    ///
    /// * `values` - Initial values for each local
    /// * `types` - CIL type flavors for each local (must match values length)
    ///
    /// # Panics
    ///
    /// Panics if values and types have different lengths.
    #[must_use]
    pub fn with_values(values: Vec<EmValue>, types: Vec<CilFlavor>) -> Self {
        assert_eq!(
            values.len(),
            types.len(),
            "values and types must have same length"
        );
        LocalVariables { values, types }
    }

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

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

    /// Sets the value of a local variable.
    ///
    /// # Arguments
    ///
    /// * `index` - The local variable index (0-based)
    /// * `value` - The value to store
    ///
    /// # Errors
    ///
    /// Returns error if index is out of bounds.
    ///
    /// # Type handling
    ///
    /// Matches .NET CLR runtime behavior: local variable types are NOT enforced
    /// at execution time. The CLR only checks types during optional verification
    /// (peverify), not at runtime. This is important for obfuscated code (e.g.,
    /// CFF-protected methods) which is always unverifiable and may store different
    /// types into the same local across different code paths.
    ///
    /// When a type mismatch is detected, the local's declared type is updated to
    /// match the stored value, ensuring subsequent loads work correctly.
    pub fn set(&mut self, index: usize, value: EmValue) -> Result<()> {
        if index >= self.values.len() {
            return Err(EmulationError::LocalIndexOutOfBounds {
                index,
                count: self.values.len(),
            }
            .into());
        }

        // Match .NET runtime behavior: accept all types for local stores.
        // If the stored value's type differs from the declared type, update the
        // declared type to match. This handles unverifiable code patterns like
        // CFF obfuscation where different code paths store different types.
        if !value.is_symbolic() {
            let found = value.cil_flavor();
            if !self.types[index].is_stack_assignable_from(&found) {
                self.types[index] = found;
            }
        }

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

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

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

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

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

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

    /// Resets all locals to their default values.
    pub fn reset(&mut self) {
        for (value, typ) in self.values.iter_mut().zip(self.types.iter()) {
            *value = EmValue::default_for_flavor(typ);
        }
    }

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

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

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

    /// Returns an iterator over (index, type, value) triples.
    pub fn iter_typed(&self) -> impl Iterator<Item = (usize, &CilFlavor, &EmValue)> {
        self.values
            .iter()
            .zip(self.types.iter())
            .enumerate()
            .map(|(i, (v, t))| (i, t, v))
    }
}

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

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

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

    #[test]
    fn test_locals_creation() {
        let locals = LocalVariables::new(vec![CilFlavor::I4, CilFlavor::I8, CilFlavor::Object]);

        assert_eq!(locals.count(), 3);
        assert_eq!(locals.get(0).unwrap(), &EmValue::I32(0));
        assert_eq!(locals.get(1).unwrap(), &EmValue::I64(0));
        assert_eq!(locals.get(2).unwrap(), &EmValue::Null);
    }

    #[test]
    fn test_locals_empty() {
        let locals = LocalVariables::empty();
        assert!(locals.is_empty());
        assert_eq!(locals.count(), 0);
    }

    #[test]
    fn test_locals_get_set() {
        let mut locals = LocalVariables::new(vec![CilFlavor::I4, CilFlavor::I8]);

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

        locals.set(1, EmValue::I64(100)).unwrap();
        assert_eq!(locals.get(1).unwrap(), &EmValue::I64(100));
    }

    #[test]
    fn test_locals_out_of_bounds() {
        let locals = LocalVariables::new(vec![CilFlavor::I4]);

        let result = locals.get(5);
        assert!(matches!(
            result,
            Err(Error::Emulation(ref e)) if matches!(e.as_ref(), EmulationError::LocalIndexOutOfBounds { index: 5, count: 1 })
        ));
    }

    #[test]
    fn test_locals_type_mismatch_accepted() {
        // Matches .NET CLR runtime behavior: local type mismatches are accepted.
        // The CLR only checks types during optional verification, not at runtime.
        let mut locals = LocalVariables::new(vec![CilFlavor::I4]);

        // Storing I64 into I4 local should succeed (type updated to match)
        let result = locals.set(0, EmValue::I64(100));
        assert!(result.is_ok());
        assert_eq!(locals.get(0).unwrap(), &EmValue::I64(100));
        assert_eq!(locals.get_type(0).unwrap(), &CilFlavor::I8);
    }

    #[test]
    fn test_locals_get_type() {
        let locals = LocalVariables::new(vec![CilFlavor::I4, CilFlavor::R8]);

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

    #[test]
    fn test_locals_reset() {
        let mut locals = LocalVariables::new(vec![CilFlavor::I4, CilFlavor::I8]);

        locals.set(0, EmValue::I32(42)).unwrap();
        locals.set(1, EmValue::I64(100)).unwrap();

        locals.reset();

        assert_eq!(locals.get(0).unwrap(), &EmValue::I32(0));
        assert_eq!(locals.get(1).unwrap(), &EmValue::I64(0));
    }

    #[test]
    fn test_locals_snapshot_restore() {
        let mut locals = LocalVariables::new(vec![CilFlavor::I4, CilFlavor::I8]);

        locals.set(0, EmValue::I32(42)).unwrap();
        let snapshot = locals.snapshot();

        locals.set(0, EmValue::I32(99)).unwrap();
        assert_eq!(locals.get(0).unwrap(), &EmValue::I32(99));

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

    #[test]
    fn test_locals_iter() {
        let locals = LocalVariables::new(vec![CilFlavor::I4, CilFlavor::I8]);

        let items: Vec<_> = locals.iter().collect();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0], (0, &EmValue::I32(0)));
        assert_eq!(items[1], (1, &EmValue::I64(0)));
    }

    #[test]
    fn test_locals_display() {
        let mut locals = LocalVariables::new(vec![CilFlavor::I4]);
        locals.set(0, EmValue::I32(42)).unwrap();

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

    #[test]
    fn test_locals_error_display() {
        let err = EmulationError::LocalIndexOutOfBounds { index: 5, count: 3 };
        assert!(format!("{err}").contains("5"));
        assert!(format!("{err}").contains("3"));
    }
}