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
//! CIL evaluation stack implementation.
//!
//! This module provides [`EvaluationStack`], the primary working area for CIL
//! bytecode execution. The evaluation stack is a last-in-first-out (LIFO) stack
//! where most CIL instructions pop operands and push results.
//!
//! # CIL Stack Semantics
//!
//! The evaluation stack follows these rules:
//! - Each method invocation starts with an empty stack
//! - Instructions pop operands and push results according to their specification
//! - At method return, the stack must contain exactly the return value (or be empty for void)
//! - At control flow merge points, stack depth and types must match
//!
//! # Overflow Protection
//!
//! The stack has a configurable maximum depth to prevent runaway execution from
//! consuming excessive memory. Exceeding this limit returns [`EmulationError::StackOverflow`](crate::emulation::EmulationError::StackOverflow).
//!
//! # Type-Checked Operations
//!
//! While [`push`](EvaluationStack::push) accepts any [`EmValue`](crate::emulation::EmValue),
//! type-checked pop methods like [`pop_i32`](EvaluationStack::pop_i32) ensure
//! type safety at runtime.

use std::fmt;

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

/// CIL evaluation stack with overflow protection.
///
/// The evaluation stack is the primary working area for CIL instructions.
/// Values are pushed and popped according to instruction semantics.
///
/// # Stack Depth Limits
///
/// The stack has a configurable maximum depth to prevent runaway execution.
/// Exceeding this limit returns an error.
///
/// # Type Safety
///
/// While the stack accepts any [`EmValue`], type-checked operations like
/// [`pop_i32`](Self::pop_i32) can ensure type safety at pop time.
///
/// # Example
///
/// ```rust
/// use dotscope::emulation::{EmValue, EvaluationStack};
///
/// let mut stack = EvaluationStack::new(100);
///
/// // Push values
/// stack.push(EmValue::I32(42)).unwrap();
/// stack.push(EmValue::I64(100)).unwrap();
///
/// // Pop values
/// let val = stack.pop().unwrap();
/// assert_eq!(val, EmValue::I64(100));
/// ```
#[derive(Clone, Debug)]
pub struct EvaluationStack {
    /// The stack storage.
    values: Vec<EmValue>,

    /// Maximum allowed stack depth.
    max_depth: usize,
}

impl EvaluationStack {
    /// Creates a new evaluation stack with the given maximum depth.
    ///
    /// # Arguments
    ///
    /// * `max_depth` - Maximum number of values allowed on the stack
    ///
    /// # Example
    ///
    /// ```rust
    /// use dotscope::emulation::EvaluationStack;
    ///
    /// let stack = EvaluationStack::new(1000);
    /// assert!(stack.is_empty());
    /// ```
    #[must_use]
    pub fn new(max_depth: usize) -> Self {
        EvaluationStack {
            values: Vec::with_capacity(max_depth.min(256)),
            max_depth,
        }
    }

    /// Creates a new evaluation stack with default maximum depth (10000).
    #[must_use]
    pub fn default_depth() -> Self {
        Self::new(10000)
    }

    /// Pushes a value onto the stack.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to push
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::StackOverflow`] if the stack is full.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dotscope::emulation::{EmValue, EvaluationStack};
    ///
    /// let mut stack = EvaluationStack::new(2);
    /// stack.push(EmValue::I32(1)).unwrap();
    /// stack.push(EmValue::I32(2)).unwrap();
    /// assert!(stack.push(EmValue::I32(3)).is_err()); // Overflow
    /// ```
    pub fn push(&mut self, value: EmValue) -> Result<()> {
        if self.values.len() >= self.max_depth {
            return Err(EmulationError::StackOverflow.into());
        }
        self.values.push(value);
        Ok(())
    }

    /// Pops a value from the stack.
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::StackUnderflow`] if the stack is empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dotscope::emulation::{EmValue, EvaluationStack};
    ///
    /// let mut stack = EvaluationStack::new(100);
    /// stack.push(EmValue::I32(42)).unwrap();
    /// let val = stack.pop().unwrap();
    /// assert_eq!(val, EmValue::I32(42));
    /// ```
    pub fn pop(&mut self) -> Result<EmValue> {
        self.values
            .pop()
            .ok_or(EmulationError::StackUnderflow.into())
    }

    /// Peeks at the top value without removing it.
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::StackUnderflow`] if the stack is empty.
    pub fn peek(&self) -> Result<&EmValue> {
        self.values
            .last()
            .ok_or(EmulationError::StackUnderflow.into())
    }

    /// Peeks at the value at the given depth from the top.
    ///
    /// Depth 0 is the top of the stack.
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::StackUnderflow`] if the depth exceeds stack size.
    pub fn peek_at(&self, depth: usize) -> Result<&EmValue> {
        if depth >= self.values.len() {
            return Err(EmulationError::StackUnderflow.into());
        }
        Ok(&self.values[self.values.len() - 1 - depth])
    }

    /// Pops a value and verifies it has the expected CIL flavor.
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::StackTypeMismatch`] if the type doesn't match.
    pub fn pop_typed(&mut self, expected: &CilFlavor) -> Result<EmValue> {
        let value = self.pop()?;
        let actual = value.cil_flavor();
        if !actual.is_compatible_with(expected) {
            // Put it back before returning error
            self.values.push(value);
            return Err(EmulationError::StackTypeMismatch {
                expected: expected.as_str(),
                found: actual.as_str(),
            }
            .into());
        }
        Ok(value)
    }

    /// Pops an I32 value from the stack.
    ///
    /// # Errors
    ///
    /// Returns error if stack is empty or top value is not I32.
    pub fn pop_i32(&mut self) -> Result<i32> {
        let value = self.pop()?;
        match value {
            EmValue::I32(v) => Ok(v),
            EmValue::Bool(v) => Ok(i32::from(v)),
            EmValue::Char(v) => Ok(v as i32),
            _ => {
                let found = value.cil_flavor();
                self.values.push(value);
                Err(EmulationError::StackTypeMismatch {
                    expected: "int32",
                    found: found.as_str(),
                }
                .into())
            }
        }
    }

    /// Pops an I64 value from the stack.
    ///
    /// # Errors
    ///
    /// Returns error if stack is empty or top value is not I64.
    pub fn pop_i64(&mut self) -> Result<i64> {
        let value = self.pop()?;
        if let EmValue::I64(v) = value {
            Ok(v)
        } else {
            let found = value.cil_flavor();
            self.values.push(value);
            Err(EmulationError::StackTypeMismatch {
                expected: "int64",
                found: found.as_str(),
            }
            .into())
        }
    }

    /// Pops an F32 value from the stack.
    ///
    /// # Errors
    ///
    /// Returns error if stack is empty or top value is not F32.
    pub fn pop_f32(&mut self) -> Result<f32> {
        let value = self.pop()?;
        if let EmValue::F32(v) = value {
            Ok(v)
        } else {
            let found = value.cil_flavor();
            self.values.push(value);
            Err(EmulationError::StackTypeMismatch {
                expected: "float32",
                found: found.as_str(),
            }
            .into())
        }
    }

    /// Pops an F64 value from the stack.
    ///
    /// # Errors
    ///
    /// Returns error if stack is empty or top value is not F64.
    pub fn pop_f64(&mut self) -> Result<f64> {
        let value = self.pop()?;
        match value {
            EmValue::F64(v) => Ok(v),
            EmValue::F32(v) => Ok(f64::from(v)), // F32 can widen to F64
            _ => {
                let found = value.cil_flavor();
                self.values.push(value);
                Err(EmulationError::StackTypeMismatch {
                    expected: "float64",
                    found: found.as_str(),
                }
                .into())
            }
        }
    }

    /// Pops an object reference from the stack (including null).
    ///
    /// # Errors
    ///
    /// Returns error if stack is empty or top value is not an object reference.
    pub fn pop_object_ref(&mut self) -> Result<EmValue> {
        let value = self.pop()?;
        match value {
            EmValue::ObjectRef(_) | EmValue::Null => Ok(value),
            _ => {
                let found = value.cil_flavor();
                self.values.push(value);
                Err(EmulationError::StackTypeMismatch {
                    expected: "object ref",
                    found: found.as_str(),
                }
                .into())
            }
        }
    }

    /// Pops two values for a binary operation.
    ///
    /// Returns (left, right) where right was on top of stack.
    ///
    /// # Errors
    ///
    /// Returns error if stack has fewer than 2 values.
    pub fn pop_binary(&mut self) -> Result<(EmValue, EmValue)> {
        let right = self.pop()?;
        let left = self.pop().inspect_err(|_| {
            // Put right back if left fails
            self.values.push(right.clone());
        })?;
        Ok((left, right))
    }

    /// Duplicates the top value on the stack.
    ///
    /// Implements the CIL `dup` instruction.
    ///
    /// # Errors
    ///
    /// Returns error if stack is empty or would overflow.
    pub fn dup(&mut self) -> Result<()> {
        let value = self.peek()?.clone();
        self.push(value)
    }

    /// Swaps the top two values on the stack.
    ///
    /// # Errors
    ///
    /// Returns error if stack has fewer than 2 values.
    pub fn swap(&mut self) -> Result<()> {
        let len = self.values.len();
        if len < 2 {
            return Err(EmulationError::StackUnderflow.into());
        }
        self.values.swap(len - 1, len - 2);
        Ok(())
    }

    /// Clears all values from the stack.
    pub fn clear(&mut self) {
        self.values.clear();
    }

    /// Returns the current depth of the stack.
    #[must_use]
    pub fn depth(&self) -> usize {
        self.values.len()
    }

    /// Returns the maximum depth of the stack.
    #[must_use]
    pub fn max_depth(&self) -> usize {
        self.max_depth
    }

    /// Returns `true` if the stack is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Returns a reference to the underlying values (bottom to top).
    #[must_use]
    pub fn values(&self) -> &[EmValue] {
        &self.values
    }

    /// Returns an iterator over stack values from bottom to top.
    pub fn iter(&self) -> impl Iterator<Item = &EmValue> {
        self.values.iter()
    }

    /// Returns an iterator over stack values from top to bottom.
    pub fn iter_top_down(&self) -> impl Iterator<Item = &EmValue> {
        self.values.iter().rev()
    }

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

    /// Restores the stack to a previous snapshot.
    ///
    /// # Arguments
    ///
    /// * `snapshot` - Previously captured stack state
    pub fn restore(&mut self, snapshot: Vec<EmValue>) {
        self.values = snapshot;
    }

    /// Checks if the stack types match expectations.
    ///
    /// Useful for verifying stack state at merge points.
    ///
    /// # Errors
    ///
    /// Returns error if stack depth or types don't match.
    pub fn verify_types(&self, expected: &[CilFlavor]) -> Result<()> {
        if self.values.len() != expected.len() {
            return Err(EmulationError::InvalidStackState {
                message: format!(
                    "stack depth mismatch: expected {}, found {}",
                    expected.len(),
                    self.values.len()
                ),
            }
            .into());
        }

        for (i, (value, exp)) in self.values.iter().zip(expected.iter()).enumerate() {
            let actual = value.cil_flavor();
            if !actual.is_compatible_with(exp) {
                return Err(EmulationError::InvalidStackState {
                    message: format!(
                        "type mismatch at position {i}: expected {exp}, found {actual}"
                    ),
                }
                .into());
            }
        }

        Ok(())
    }
}

impl Default for EvaluationStack {
    fn default() -> Self {
        Self::default_depth()
    }
}

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

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

    #[test]
    fn test_stack_push_pop() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I32(2)).unwrap();
        stack.push(EmValue::I32(3)).unwrap();

        assert_eq!(stack.depth(), 3);
        assert_eq!(stack.pop().unwrap(), EmValue::I32(3));
        assert_eq!(stack.pop().unwrap(), EmValue::I32(2));
        assert_eq!(stack.pop().unwrap(), EmValue::I32(1));
        assert!(stack.is_empty());
    }

    #[test]
    fn test_stack_overflow() {
        let mut stack = EvaluationStack::new(2);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I32(2)).unwrap();

        let result = stack.push(EmValue::I32(3));
        assert!(matches!(
            result,
            Err(Error::Emulation(ref e)) if matches!(e.as_ref(), EmulationError::StackOverflow)
        ));
    }

    #[test]
    fn test_stack_underflow() {
        let mut stack = EvaluationStack::new(10);

        let result = stack.pop();
        assert!(matches!(
            result,
            Err(Error::Emulation(ref e)) if matches!(e.as_ref(), EmulationError::StackUnderflow)
        ));
    }

    #[test]
    fn test_stack_peek() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(42)).unwrap();

        assert_eq!(stack.peek().unwrap(), &EmValue::I32(42));
        assert_eq!(stack.depth(), 1); // Peek doesn't remove
    }

    #[test]
    fn test_stack_peek_at() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I32(2)).unwrap();
        stack.push(EmValue::I32(3)).unwrap();

        assert_eq!(stack.peek_at(0).unwrap(), &EmValue::I32(3)); // Top
        assert_eq!(stack.peek_at(1).unwrap(), &EmValue::I32(2));
        assert_eq!(stack.peek_at(2).unwrap(), &EmValue::I32(1)); // Bottom
        assert!(stack.peek_at(3).is_err());
    }

    #[test]
    fn test_stack_pop_typed() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(42)).unwrap();

        let value = stack.pop_typed(&CilFlavor::I4).unwrap();
        assert_eq!(value, EmValue::I32(42));

        stack.push(EmValue::I64(100)).unwrap();
        let result = stack.pop_typed(&CilFlavor::I4);
        assert!(matches!(
            result,
            Err(Error::Emulation(ref e)) if matches!(e.as_ref(), EmulationError::StackTypeMismatch { .. })
        ));
        // Value should be put back
        assert_eq!(stack.depth(), 1);
    }

    #[test]
    fn test_stack_pop_i32() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(42)).unwrap();
        assert_eq!(stack.pop_i32().unwrap(), 42);

        stack.push(EmValue::Bool(true)).unwrap();
        assert_eq!(stack.pop_i32().unwrap(), 1);

        stack.push(EmValue::Char('A')).unwrap();
        assert_eq!(stack.pop_i32().unwrap(), 65);

        stack.push(EmValue::I64(100)).unwrap();
        assert!(stack.pop_i32().is_err());
    }

    #[test]
    fn test_stack_pop_object_ref() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::Null).unwrap();
        let val = stack.pop_object_ref().unwrap();
        assert_eq!(val, EmValue::Null);

        stack.push(EmValue::ObjectRef(HeapRef::new(1))).unwrap();
        let val = stack.pop_object_ref().unwrap();
        assert!(matches!(val, EmValue::ObjectRef(_)));

        stack.push(EmValue::I32(0)).unwrap();
        assert!(stack.pop_object_ref().is_err());
    }

    #[test]
    fn test_stack_pop_binary() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(10)).unwrap();
        stack.push(EmValue::I32(20)).unwrap();

        let (left, right) = stack.pop_binary().unwrap();
        assert_eq!(left, EmValue::I32(10));
        assert_eq!(right, EmValue::I32(20));
        assert!(stack.is_empty());
    }

    #[test]
    fn test_stack_dup() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(42)).unwrap();
        stack.dup().unwrap();

        assert_eq!(stack.depth(), 2);
        assert_eq!(stack.pop().unwrap(), EmValue::I32(42));
        assert_eq!(stack.pop().unwrap(), EmValue::I32(42));
    }

    #[test]
    fn test_stack_swap() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I32(2)).unwrap();

        stack.swap().unwrap();

        assert_eq!(stack.pop().unwrap(), EmValue::I32(1));
        assert_eq!(stack.pop().unwrap(), EmValue::I32(2));
    }

    #[test]
    fn test_stack_clear() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I32(2)).unwrap();

        stack.clear();
        assert!(stack.is_empty());
    }

    #[test]
    fn test_stack_snapshot_restore() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I32(2)).unwrap();

        let snapshot = stack.snapshot();

        stack.push(EmValue::I32(3)).unwrap();
        assert_eq!(stack.depth(), 3);

        stack.restore(snapshot);
        assert_eq!(stack.depth(), 2);
    }

    #[test]
    fn test_stack_verify_types() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I64(2)).unwrap();

        let result = stack.verify_types(&[CilFlavor::I4, CilFlavor::I8]);
        assert!(result.is_ok());

        let result = stack.verify_types(&[CilFlavor::I4, CilFlavor::I4]);
        assert!(result.is_err());

        let result = stack.verify_types(&[CilFlavor::I4]);
        assert!(result.is_err()); // Wrong depth
    }

    #[test]
    fn test_stack_display() {
        let mut stack = EvaluationStack::new(10);

        stack.push(EmValue::I32(1)).unwrap();
        stack.push(EmValue::I64(2)).unwrap();

        let display = format!("{stack}");
        assert!(display.contains("1"));
        assert!(display.contains("2L"));
    }
}