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
//!
//! Sequence Points parsing and access for PortablePDB MethodDebugInformation.
//!
//! This module provides types and functions to parse and expose sequence points from the
//! PortablePDB format, mapping IL offsets to source code locations for debugging purposes.
//!
//! # Architecture
//!
//! Sequence points are stored in the [`crate::metadata::tables::MethodDebugInformation`] table as a compressed blob.
//! This module parses the blob and exposes a user-friendly API for accessing sequence point data.
//!
//! # Key Components
//!
//! - [`crate::metadata::sequencepoints::SequencePoint`] - Represents a single mapping from IL offset to source code location.
//! - [`crate::metadata::sequencepoints::SequencePoints`] - Collection of sequence points for a method.
//! - [`crate::metadata::sequencepoints::parse_sequence_points`] - Parses a sequence points blob into a collection.
//!
//! # Usage Examples
//!
//! ```rust,no_run
//! use dotscope::metadata::sequencepoints::{parse_sequence_points, SequencePoints};
//!
//! let blob: &[u8] = &[1, 10, 2, 0, 5];
//! let points = parse_sequence_points(blob)?;
//! assert_eq!(points.0.len(), 1);
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Error Handling
//!
//! Returns [`crate::Error`] if the blob is malformed or contains invalid compressed data.
//!
//! # Thread Safety
//!
//! All types in this module are [`Send`] and [`Sync`] because they contain only owned data.
//!
//! # Integration
//!
//! This module integrates with:
//! - Method debug information tables - for exposing parsed sequence points per method
//! - [`crate::file::parser::Parser`] - for binary parsing utilities
//!
//! # Sequence Points Blob Format
//!
//! The sequence points blob in PortablePDB is a compressed, delta-encoded list of mappings from IL offsets to source code locations.
//! It is stored as a blob in the [`crate::metadata::tables::MethodDebugInformation`] table.
//!
//! ## Layout
//!
//! Each sequence point entry consists of:
//! - **IL Offset**: (compressed unsigned int)
//! - **Start Line**: (compressed unsigned int for first entry, compressed signed int delta for subsequent entries)
//! - **Start Column**: (compressed unsigned int for first entry, compressed signed int delta for subsequent entries)
//! - **End Line Delta**: (compressed unsigned int, added to start line)
//! - **End Column Delta**: (compressed unsigned int, added to start column)
//!
//! The first entry uses absolute values for start line/col, subsequent entries use deltas.
//! All values are encoded using ECMA-335 compressed integer encoding (see II.23.2).
//!
//! ## Example
//!
//! For two sequence points:
//! - First: il_offset=1, start_line=10, start_col=2, end_line_delta=0, end_col_delta=5
//! - Second: il_offset_delta=2, start_line_delta=1, start_col_delta=1, end_line_delta=0, end_col_delta=2
//!
//! Encoded as:
//! ```text
//! [1, 10, 2, 0, 5, 4, 2, 2, 0, 2]
//! ```
//! Where 4 is the compressed int for delta 2, and 2 is the compressed int for delta 1.
//!
//! ## Hidden Sequence Points
//!
//! A sequence point is considered hidden if its start line is 0xFEEFEE. This is used to mark compiler-generated or non-user code.
//! The value 0xFEEFEE is encoded as a compressed unsigned int: [0xC0, 0xFE, 0xEF, 0xEE].
//!
//! ## References
//!
//! - [ECMA-335 II.24.2.6.2](https://www.ecma-international.org/publications-and-standards/standards/ecma-335/)
//! - [PortablePDB Spec](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#sequence-points)

use crate::{
    file::parser::Parser,
    utils::{write_compressed_int, write_compressed_uint},
    Result,
};

/// The magic line number that indicates a hidden sequence point.
/// This value (0xFEEFEE) is used by .NET compilers to mark compiler-generated
/// or non-user code that should not be shown in debuggers.
pub const HIDDEN_SEQUENCE_POINT_LINE: u32 = 0x00FE_EFEE;

/// Represents a single sequence point mapping IL offset to source code location.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequencePoint {
    /// Offset in the method's IL stream.
    pub il_offset: u32,
    /// Starting line in the source file.
    pub start_line: u32,
    /// Starting column in the source file.
    pub start_col: u16,
    /// Ending line in the source file.
    pub end_line: u32,
    /// Ending column in the source file.
    pub end_col: u16,
    /// True if this is a hidden sequence point (start_line == 0xFEEFEE).
    pub is_hidden: bool,
}

impl SequencePoint {
    /// Creates a new sequence point with validation.
    ///
    /// This constructor validates that the source code range is valid and automatically
    /// computes the `is_hidden` flag based on the start line.
    ///
    /// # Arguments
    ///
    /// * `il_offset` - Offset in the method's IL stream
    /// * `start_line` - Starting line in the source file (1-based, or 0xFEEFEE for hidden)
    /// * `start_col` - Starting column in the source file (1-based)
    /// * `end_line` - Ending line in the source file (must be >= start_line for non-hidden)
    /// * `end_col` - Ending column in the source file
    ///
    /// # Returns
    ///
    /// Returns `Some(SequencePoint)` if the parameters are valid, `None` otherwise.
    ///
    /// # Validation Rules
    ///
    /// For non-hidden sequence points:
    /// - `end_line` must be greater than or equal to `start_line`
    /// - When `end_line == start_line`, `end_col` must be greater than or equal to `start_col`
    ///
    /// Hidden sequence points (start_line == 0xFEEFEE) bypass range validation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::sequencepoints::SequencePoint;
    ///
    /// // Valid sequence point
    /// let sp = SequencePoint::new(0, 10, 5, 10, 15);
    /// assert!(sp.is_some());
    /// assert!(!sp.unwrap().is_hidden);
    ///
    /// // Invalid: end_col < start_col on same line
    /// let invalid = SequencePoint::new(0, 10, 15, 10, 5);
    /// assert!(invalid.is_none());
    ///
    /// // Hidden sequence point (no range validation)
    /// let hidden = SequencePoint::new(0, 0xFEEFEE, 0, 0xFEEFEE, 0);
    /// assert!(hidden.is_some());
    /// assert!(hidden.unwrap().is_hidden);
    /// ```
    #[must_use]
    pub fn new(
        il_offset: u32,
        start_line: u32,
        start_col: u16,
        end_line: u32,
        end_col: u16,
    ) -> Option<Self> {
        let is_hidden = start_line == HIDDEN_SEQUENCE_POINT_LINE;

        // Validate source range for non-hidden sequence points
        if !is_hidden {
            // End line must be >= start line
            if end_line < start_line {
                return None;
            }
            // When on same line, end column must be >= start column
            if end_line == start_line && end_col < start_col {
                return None;
            }
        }

        Some(Self {
            il_offset,
            start_line,
            start_col,
            end_line,
            end_col,
            is_hidden,
        })
    }

    /// Creates a hidden sequence point at the given IL offset.
    ///
    /// Hidden sequence points are used to mark compiler-generated code that should
    /// not be displayed in debuggers. They use the special line number 0xFEEFEE.
    ///
    /// # Arguments
    ///
    /// * `il_offset` - Offset in the method's IL stream
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::sequencepoints::{SequencePoint, HIDDEN_SEQUENCE_POINT_LINE};
    ///
    /// let hidden = SequencePoint::hidden(42);
    /// assert!(hidden.is_hidden);
    /// assert_eq!(hidden.il_offset, 42);
    /// assert_eq!(hidden.start_line, HIDDEN_SEQUENCE_POINT_LINE);
    /// ```
    #[must_use]
    pub fn hidden(il_offset: u32) -> Self {
        Self {
            il_offset,
            start_line: HIDDEN_SEQUENCE_POINT_LINE,
            start_col: 0,
            end_line: HIDDEN_SEQUENCE_POINT_LINE,
            end_col: 0,
            is_hidden: true,
        }
    }
}

/// Collection of sequence points for a method.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SequencePoints(pub Vec<SequencePoint>);

impl SequencePoints {
    /// Returns the sequence point for a given IL offset, if any.
    #[must_use]
    pub fn find_by_il_offset(&self, il_offset: u32) -> Option<&SequencePoint> {
        self.0.iter().find(|sp| sp.il_offset == il_offset)
    }

    /// Serializes the sequence points to binary format.
    ///
    /// Converts the sequence points collection back to the compressed blob format
    /// used in PortablePDB MethodDebugInformation table. The encoding uses delta
    /// compression and ECMA-335 compressed integer format.
    ///
    /// # Returns
    ///
    /// A vector of bytes representing the encoded sequence points blob.
    ///
    /// # Format
    ///
    /// The first sequence point uses absolute values, subsequent points use deltas:
    /// - IL Offset: absolute for first, delta for subsequent
    /// - Start Line: absolute for first, signed delta for subsequent  
    /// - Start Column: absolute for first, signed delta for subsequent
    /// - End Line Delta: unsigned delta from start line
    /// - End Column Delta: unsigned delta from start column
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use dotscope::metadata::sequencepoints::{SequencePoints, SequencePoint};
    /// let points = SequencePoints(vec![
    ///     SequencePoint {
    ///         il_offset: 1,
    ///         start_line: 10,
    ///         start_col: 2,
    ///         end_line: 10,
    ///         end_col: 7,
    ///         is_hidden: false,
    ///     }
    /// ]);
    /// let bytes = points.to_bytes();
    /// assert_eq!(bytes, vec![1, 10, 2, 0, 5]); // il_offset=1, start_line=10, start_col=2, end_line_delta=0, end_col_delta=5
    /// ```
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buffer = Vec::new();

        if self.0.is_empty() {
            return buffer;
        }

        let mut prev_il_offset = 0u32;
        let mut prev_start_line = 0u32;
        let mut prev_start_col = 0u16;

        for (i, point) in self.0.iter().enumerate() {
            let is_first = i == 0;

            // IL Offset (absolute for first, delta for subsequent)
            let il_offset_value = if is_first {
                point.il_offset
            } else {
                point.il_offset - prev_il_offset
            };
            write_compressed_uint(il_offset_value, &mut buffer);

            // Start Line (absolute for first, signed delta for subsequent)
            if is_first {
                write_compressed_uint(point.start_line, &mut buffer);
            } else {
                #[allow(clippy::cast_possible_wrap)]
                let delta = point.start_line as i32 - prev_start_line as i32;
                write_compressed_int(delta, &mut buffer);
            }

            // Start Column (absolute for first, signed delta for subsequent)
            if is_first {
                write_compressed_uint(u32::from(point.start_col), &mut buffer);
            } else {
                let delta = i32::from(point.start_col) - i32::from(prev_start_col);
                write_compressed_int(delta, &mut buffer);
            }

            // End Line Delta (unsigned delta from start line)
            let end_line_delta = point.end_line - point.start_line;
            write_compressed_uint(end_line_delta, &mut buffer);

            // End Column Delta (unsigned delta from start column)
            let end_col_delta = point.end_col - point.start_col;
            write_compressed_uint(u32::from(end_col_delta), &mut buffer);

            // Update previous values for next iteration
            prev_il_offset = point.il_offset;
            prev_start_line = point.start_line;
            prev_start_col = point.start_col;
        }

        buffer
    }
}

/// Parses a PortablePDB sequence points blob into a SequencePoints collection.
///
/// # Arguments
/// * `blob` - The raw sequence points blob from MethodDebugInformation.
///
/// # Returns
/// * `Ok(SequencePoints)` on success, or `Err(OutOfBounds)` on failure.
///
/// # Errors
/// Returns an error if:
/// - The blob is malformed or truncated
/// - Compressed integer values cannot be decoded
/// - IL offsets or line/column deltas are out of valid range
pub fn parse_sequence_points(blob: &[u8]) -> Result<SequencePoints> {
    let mut parser = Parser::new(blob);
    let mut points = Vec::new();
    let mut il_offset = 0u32;
    let mut start_line = 0u32;
    let mut start_col = 0u16;
    let mut first = true;

    // Document reference is handled at a higher level if present.
    while parser.has_more_data() {
        let il_offset_delta = parser.read_compressed_uint()?;
        il_offset = if first {
            il_offset_delta
        } else {
            il_offset + il_offset_delta
        };

        let start_line_delta = if first {
            parser.read_compressed_uint()? // Absolute
        } else {
            #[allow(clippy::cast_sign_loss)]
            {
                parser.read_compressed_int()? as u32 // Delta
            }
        };
        start_line = if first {
            start_line_delta
        } else {
            start_line.wrapping_add(start_line_delta)
        };

        let start_col_delta = if first {
            #[allow(clippy::cast_possible_truncation)]
            {
                parser.read_compressed_uint()? as u16 // Absolute
            }
        } else {
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            {
                parser.read_compressed_int()? as u16 // Delta
            }
        };
        start_col = if first {
            start_col_delta
        } else {
            start_col.wrapping_add(start_col_delta)
        };

        let end_line_delta = parser.read_compressed_uint()?;
        #[allow(clippy::cast_possible_truncation)]
        let end_col_delta = parser.read_compressed_uint()? as u16;
        let end_line = start_line + end_line_delta;
        let end_col = start_col + end_col_delta;

        let is_hidden = start_line == HIDDEN_SEQUENCE_POINT_LINE;
        points.push(SequencePoint {
            il_offset,
            start_line,
            start_col,
            end_line,
            end_col,
            is_hidden,
        });
        first = false;
    }
    Ok(SequencePoints(points))
}

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

    #[test]
    fn parse_empty_blob() {
        let blob: &[u8] = &[];
        let result = parse_sequence_points(blob);
        assert!(result.is_ok());
        assert!(result.unwrap().0.is_empty());
    }

    #[test]
    fn parse_single_sequence_point() {
        // This is a synthetic blob: absolute il_offset=1, start_line=10, start_col=2, end_line_delta=0, end_col_delta=5
        let blob: &[u8] = &[1, 10, 2, 0, 5];
        let result = parse_sequence_points(blob).unwrap();
        assert_eq!(result.0.len(), 1);
        let sp = &result.0[0];
        assert_eq!(sp.il_offset, 1);
        assert_eq!(sp.start_line, 10);
        assert_eq!(sp.start_col, 2);
        assert_eq!(sp.end_line, 10);
        assert_eq!(sp.end_col, 7);
        assert!(!sp.is_hidden);
    }

    #[test]
    fn parse_hidden_sequence_point() {
        // il_offset=0, start_line=HIDDEN_SEQUENCE_POINT_LINE, start_col=0, end_line_delta=0, end_col_delta=0
        // 0xFEEFEE as ECMA-335 compressed uint: [0xC0, 0xFE, 0xEF, 0xEE]
        // Only 5 fields needed: il_offset, start_line, start_col, end_line_delta, end_col_delta
        let blob: &[u8] = &[0, 0xC0, 0xFE, 0xEF, 0xEE, 0, 0, 0];
        let result = parse_sequence_points(blob);
        if let Ok(points) = result {
            let sp = &points.0[0];
            assert!(sp.is_hidden);
            assert_eq!(sp.start_line, HIDDEN_SEQUENCE_POINT_LINE);
            assert_eq!(sp.il_offset, 0);
            assert_eq!(sp.start_col, 0);
            assert_eq!(sp.end_line, HIDDEN_SEQUENCE_POINT_LINE);
            assert_eq!(sp.end_col, 0);
        } else {
            panic!("Hidden sequence point parse failed: {result:?}");
        }
    }

    #[test]
    fn parse_multiple_sequence_points_with_deltas() {
        // First: il_offset=1, start_line=10, start_col=2, end_line_delta=0, end_col_delta=5
        // Second: il_offset_delta=2, start_line_delta=1, start_col_delta=1, end_line_delta=0, end_col_delta=2
        // All values must be ECMA-335 compressed ints:
        // 1, 10, 2, 0, 5, 4, 2, 2, 0, 2
        let blob: &[u8] = &[1, 10, 2, 0, 5, 4, 2, 2, 0, 2];
        let result = parse_sequence_points(blob).unwrap();
        assert_eq!(result.0.len(), 2);
        let sp0 = &result.0[0];
        let sp1 = &result.0[1];
        assert_eq!(sp0.il_offset, 1);
        assert_eq!(sp0.start_line, 10);
        assert_eq!(sp0.start_col, 2);
        assert_eq!(sp0.end_line, 10);
        assert_eq!(sp0.end_col, 7);
        assert_eq!(sp1.il_offset, 5); // 1 + 4 (delta for 2 is 4 in compressed int)
        assert_eq!(sp1.start_line, 11); // 10 + 1 (delta for 1 is 2 in compressed int)
        assert_eq!(sp1.start_col, 3); // 2 + 1 (delta for 1 is 2 in compressed int)
        assert_eq!(sp1.end_line, 11);
        assert_eq!(sp1.end_col, 5);
    }

    // Tests for SequencePoint::new constructor

    #[test]
    fn new_valid_single_line_sequence_point() {
        let sp = SequencePoint::new(0, 10, 5, 10, 15);
        assert!(sp.is_some());
        let sp = sp.unwrap();
        assert_eq!(sp.il_offset, 0);
        assert_eq!(sp.start_line, 10);
        assert_eq!(sp.start_col, 5);
        assert_eq!(sp.end_line, 10);
        assert_eq!(sp.end_col, 15);
        assert!(!sp.is_hidden);
    }

    #[test]
    fn new_valid_multi_line_sequence_point() {
        let sp = SequencePoint::new(42, 10, 5, 15, 3);
        assert!(sp.is_some());
        let sp = sp.unwrap();
        assert_eq!(sp.il_offset, 42);
        assert_eq!(sp.start_line, 10);
        assert_eq!(sp.start_col, 5);
        assert_eq!(sp.end_line, 15);
        assert_eq!(sp.end_col, 3);
        assert!(!sp.is_hidden);
    }

    #[test]
    fn new_invalid_end_line_before_start() {
        let sp = SequencePoint::new(0, 10, 5, 5, 15);
        assert!(sp.is_none(), "Should reject end_line < start_line");
    }

    #[test]
    fn new_invalid_end_col_before_start_same_line() {
        let sp = SequencePoint::new(0, 10, 15, 10, 5);
        assert!(
            sp.is_none(),
            "Should reject end_col < start_col on same line"
        );
    }

    #[test]
    fn new_valid_end_col_equals_start_col() {
        // Zero-width span is valid (cursor position)
        let sp = SequencePoint::new(0, 10, 5, 10, 5);
        assert!(sp.is_some());
        let sp = sp.unwrap();
        assert_eq!(sp.start_col, sp.end_col);
    }

    #[test]
    fn new_hidden_sequence_point() {
        let sp = SequencePoint::new(
            0,
            HIDDEN_SEQUENCE_POINT_LINE,
            0,
            HIDDEN_SEQUENCE_POINT_LINE,
            0,
        );
        assert!(sp.is_some());
        let sp = sp.unwrap();
        assert!(sp.is_hidden);
        assert_eq!(sp.start_line, HIDDEN_SEQUENCE_POINT_LINE);
    }

    #[test]
    fn hidden_constructor() {
        let sp = SequencePoint::hidden(42);
        assert!(sp.is_hidden);
        assert_eq!(sp.il_offset, 42);
        assert_eq!(sp.start_line, HIDDEN_SEQUENCE_POINT_LINE);
        assert_eq!(sp.start_col, 0);
        assert_eq!(sp.end_line, HIDDEN_SEQUENCE_POINT_LINE);
        assert_eq!(sp.end_col, 0);
    }
}