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
use crate::common::*;
use crate::FallibleIterator;

/// These values correspond to the BinaryAnnotationOpcode enum from the
/// cvinfo.h
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum BinaryAnnotationOpcode {
    /// Link time pdb contains PADDINGs.
    ///
    /// These are represented with the 0 opcode which is in some PDB
    /// implementation called "invalid".
    Eof = 0,
    /// param : start offset
    CodeOffset = 1,
    /// param : nth separated code chunk (main code chunk == 0)
    ChangeCodeOffsetBase = 2,
    /// param : delta of offset
    ChangeCodeOffset = 3,
    /// param : length of code, default next start
    ChangeCodeLength = 4,
    /// param : fileId
    ChangeFile = 5,
    /// param : line offset (signed)
    ChangeLineOffset = 6,
    /// param : how many lines, default 1
    ChangeLineEndDelta = 7,
    /// param : either 1 (default, for statement)
    ///         or 0 (for expression)
    ChangeRangeKind = 8,
    /// param : start column number, 0 means no column info
    ChangeColumnStart = 9,
    /// param : end column number delta (signed)
    ChangeColumnEndDelta = 10,
    /// param : ((sourceDelta << 4) | CodeDelta)
    ChangeCodeOffsetAndLineOffset = 11,
    /// param : codeLength, codeOffset
    ChangeCodeLengthAndCodeOffset = 12,
    /// param : end column number
    ChangeColumnEnd = 13,
}

impl BinaryAnnotationOpcode {
    fn parse(value: u32) -> Result<Self> {
        Ok(match value {
            0 => Self::Eof,
            1 => Self::CodeOffset,
            2 => Self::ChangeCodeOffsetBase,
            3 => Self::ChangeCodeOffset,
            4 => Self::ChangeCodeLength,
            5 => Self::ChangeFile,
            6 => Self::ChangeLineOffset,
            7 => Self::ChangeLineEndDelta,
            8 => Self::ChangeRangeKind,
            9 => Self::ChangeColumnStart,
            10 => Self::ChangeColumnEndDelta,
            11 => Self::ChangeCodeOffsetAndLineOffset,
            12 => Self::ChangeCodeLengthAndCodeOffset,
            13 => Self::ChangeColumnEnd,
            _ => return Err(Error::UnknownBinaryAnnotation(value)),
        })
    }
}

/// Represents a parsed `BinaryAnnotation`.
///
/// Binary annotations are used by `S_INLINESITE` to encode opcodes for how to
/// evaluate the state changes for inline information.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BinaryAnnotation {
    /// Sets the code offset to the given absolute value.
    CodeOffset(u32),
    /// Sets the base for all code offsets to the given absolute value. All following code offsets
    /// are relative to this base value.
    ChangeCodeOffsetBase(u32),
    /// **Emitting**. Advances the code offset by the given value.
    ///
    /// This annotation emits a line record. The length of the covered code block can be established
    /// by a following `ChangeCodeLength` annotation, or by the offset of the next emitted record.
    ChangeCodeOffset(u32),
    /// Adjusts the code length of the previously emitted line record. The code length resets with
    /// every line record.
    ChangeCodeLength(u32),
    /// Sets the file index of following line records.
    ChangeFile(FileIndex),
    /// Advances the line number by the given value.
    ChangeLineOffset(i32),
    /// Sets the number of source lines covered by following line records. Defaults to `1`.
    ChangeLineEndDelta(u32),
    /// Sets the kind of the line record. Defaults to `Statement`.
    ChangeRangeKind(u32),
    /// Sets the start column number. Defaults to `None`.
    ChangeColumnStart(u32),
    /// Advances the end column number by the given value.
    ChangeColumnEndDelta(i32),
    /// **Emitting**. Advances the code offset and the line number by the given values.
    ///
    /// This annotation emits a line record. The length of the covered code block can be established
    /// by a following `ChangeCodeLength` annotation, or by the offset of the next emitted record.
    ChangeCodeOffsetAndLineOffset(u32, i32),
    /// **Emitting**. Sets the code length and advances the code offset by the given value.
    ///
    /// This annotation emits a line record that is valid for the given code length. This is usually
    /// issued as one of the last annotations, as there is no subsequent line record to derive the
    /// code length from.
    ChangeCodeLengthAndCodeOffset(u32, u32),
    /// Sets the end column number.
    ChangeColumnEnd(u32),
}

impl BinaryAnnotation {
    /// Does this annotation emit a line info?
    pub fn emits_line_info(self) -> bool {
        matches!(
            self,
            BinaryAnnotation::ChangeCodeOffset(..)
                | BinaryAnnotation::ChangeCodeOffsetAndLineOffset(..)
                | BinaryAnnotation::ChangeCodeLengthAndCodeOffset(..)
        )
    }
}

/// An iterator over binary annotations used by `S_INLINESITE`.
#[derive(Clone, Debug, Default)]
pub struct BinaryAnnotationsIter<'t> {
    buffer: ParseBuffer<'t>,
}

impl<'t> BinaryAnnotationsIter<'t> {
    /// Parse a compact version of an unsigned integer.
    ///
    /// This implements `CVUncompressData`, which can decode numbers no larger than 0x1FFFFFFF. It
    /// seems that values compressed this way are only used for binary annotations at this point.
    fn uncompress_next(&mut self) -> Result<u32> {
        let b1 = u32::from(self.buffer.parse::<u8>()?);
        if (b1 & 0x80) == 0x00 {
            let value = b1;
            return Ok(value);
        }

        let b2 = u32::from(self.buffer.parse::<u8>()?);
        if (b1 & 0xc0) == 0x80 {
            let value = (b1 & 0x3f) << 8 | b2;
            return Ok(value);
        }

        let b3 = u32::from(self.buffer.parse::<u8>()?);
        let b4 = u32::from(self.buffer.parse::<u8>()?);
        if (b1 & 0xe0) == 0xc0 {
            let value = ((b1 & 0x1f) << 24) | (b2 << 16) | (b3 << 8) | b4;
            return Ok(value);
        }

        Err(Error::InvalidCompressedAnnotation)
    }
}

/// Resembles `DecodeSignedInt32`.
fn decode_signed_operand(value: u32) -> i32 {
    if value & 1 != 0 {
        -((value >> 1) as i32)
    } else {
        (value >> 1) as i32
    }
}

impl<'t> FallibleIterator for BinaryAnnotationsIter<'t> {
    type Item = BinaryAnnotation;
    type Error = Error;

    fn next(&mut self) -> Result<Option<Self::Item>> {
        if self.buffer.is_empty() {
            return Ok(None);
        }

        let op = self.uncompress_next()?;
        let annotation = match BinaryAnnotationOpcode::parse(op)? {
            BinaryAnnotationOpcode::Eof => {
                // This makes the end of the stream
                self.buffer = ParseBuffer::default();
                return Ok(None);
            }
            BinaryAnnotationOpcode::CodeOffset => {
                BinaryAnnotation::CodeOffset(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeCodeOffsetBase => {
                BinaryAnnotation::ChangeCodeOffsetBase(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeCodeOffset => {
                BinaryAnnotation::ChangeCodeOffset(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeCodeLength => {
                BinaryAnnotation::ChangeCodeLength(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeFile => {
                BinaryAnnotation::ChangeFile(FileIndex(self.uncompress_next()?))
            }
            BinaryAnnotationOpcode::ChangeLineOffset => {
                BinaryAnnotation::ChangeLineOffset(decode_signed_operand(self.uncompress_next()?))
            }
            BinaryAnnotationOpcode::ChangeLineEndDelta => {
                BinaryAnnotation::ChangeLineEndDelta(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeRangeKind => {
                BinaryAnnotation::ChangeRangeKind(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeColumnStart => {
                BinaryAnnotation::ChangeColumnStart(self.uncompress_next()?)
            }
            BinaryAnnotationOpcode::ChangeColumnEndDelta => BinaryAnnotation::ChangeColumnEndDelta(
                decode_signed_operand(self.uncompress_next()?),
            ),
            BinaryAnnotationOpcode::ChangeCodeOffsetAndLineOffset => {
                let operand = self.uncompress_next()?;
                BinaryAnnotation::ChangeCodeOffsetAndLineOffset(
                    operand & 0xf,
                    decode_signed_operand(operand >> 4),
                )
            }
            BinaryAnnotationOpcode::ChangeCodeLengthAndCodeOffset => {
                BinaryAnnotation::ChangeCodeLengthAndCodeOffset(
                    self.uncompress_next()?,
                    self.uncompress_next()?,
                )
            }
            BinaryAnnotationOpcode::ChangeColumnEnd => {
                BinaryAnnotation::ChangeColumnEnd(self.uncompress_next()?)
            }
        };

        Ok(Some(annotation))
    }
}

/// Binary annotations of a symbol.
///
/// The binary annotation mechanism supports recording a list of annotations in an instruction
/// stream. The X64 unwind code and the DWARF standard have a similar design.
///
/// Binary annotations are primarily used as line programs for inline function calls.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct BinaryAnnotations<'t> {
    data: &'t [u8],
}

impl<'t> BinaryAnnotations<'t> {
    /// Creates a new instance of binary annotations.
    pub(crate) fn new(data: &'t [u8]) -> Self {
        BinaryAnnotations { data }
    }

    /// Iterates through binary annotations.
    pub fn iter(&self) -> BinaryAnnotationsIter<'t> {
        BinaryAnnotationsIter {
            buffer: ParseBuffer::from(self.data),
        }
    }
}

#[test]
fn test_binary_annotation_iter() {
    let inp = b"\x0b\x03\x06\n\x03\x08\x06\x06\x03-\x06\x08\x03\x07\x0br\x06\x06\x0c\x03\x07\x06\x0f\x0c\x06\x05\x00\x00";
    let annotations = BinaryAnnotations::new(inp)
        .iter()
        .collect::<Vec<_>>()
        .unwrap();

    assert_eq!(
        annotations,
        vec![
            BinaryAnnotation::ChangeCodeOffsetAndLineOffset(3, 0),
            BinaryAnnotation::ChangeLineOffset(5),
            BinaryAnnotation::ChangeCodeOffset(8),
            BinaryAnnotation::ChangeLineOffset(3),
            BinaryAnnotation::ChangeCodeOffset(45),
            BinaryAnnotation::ChangeLineOffset(4),
            BinaryAnnotation::ChangeCodeOffset(7),
            BinaryAnnotation::ChangeCodeOffsetAndLineOffset(2, -3),
            BinaryAnnotation::ChangeLineOffset(3),
            BinaryAnnotation::ChangeCodeLengthAndCodeOffset(3, 7),
            BinaryAnnotation::ChangeLineOffset(-7),
            BinaryAnnotation::ChangeCodeLengthAndCodeOffset(6, 5)
        ]
    );

    let inp = b"\x03P\x06\x0e\x03\x0c\x06\x04\x032\x06\x06\x03T\x0b#\x0b\\\x0bC\x0b/\x06\x04\x0c-\t\x03;\x06\x1d\x0c\x05\x06\x00\x00";
    let annotations = BinaryAnnotations::new(inp)
        .iter()
        .collect::<Vec<_>>()
        .unwrap();

    assert_eq!(
        annotations,
        vec![
            BinaryAnnotation::ChangeCodeOffset(80),
            BinaryAnnotation::ChangeLineOffset(7),
            BinaryAnnotation::ChangeCodeOffset(12),
            BinaryAnnotation::ChangeLineOffset(2),
            BinaryAnnotation::ChangeCodeOffset(50),
            BinaryAnnotation::ChangeLineOffset(3),
            BinaryAnnotation::ChangeCodeOffset(84),
            BinaryAnnotation::ChangeCodeOffsetAndLineOffset(3, 1),
            BinaryAnnotation::ChangeCodeOffsetAndLineOffset(12, -2),
            BinaryAnnotation::ChangeCodeOffsetAndLineOffset(3, 2),
            BinaryAnnotation::ChangeCodeOffsetAndLineOffset(15, 1),
            BinaryAnnotation::ChangeLineOffset(2),
            BinaryAnnotation::ChangeCodeLengthAndCodeOffset(45, 9),
            BinaryAnnotation::ChangeCodeOffset(59),
            BinaryAnnotation::ChangeLineOffset(-14),
            BinaryAnnotation::ChangeCodeLengthAndCodeOffset(5, 6),
        ]
    );
}