Coverage Report

Created: 2024-10-16 07:58

/rust/registry/src/index.crates.io-6f17d22bba15001f/gimli-0.29.0/src/read/line.rs
Line
Count
Source (jump to first uncovered line)
1
use alloc::vec::Vec;
2
use core::fmt;
3
use core::num::{NonZeroU64, Wrapping};
4
use core::result;
5
6
use crate::common::{
7
    DebugLineOffset, DebugLineStrOffset, DebugStrOffset, DebugStrOffsetsIndex, Encoding, Format,
8
    LineEncoding, SectionId,
9
};
10
use crate::constants;
11
use crate::endianity::Endianity;
12
use crate::read::{AttributeValue, EndianSlice, Error, Reader, ReaderOffset, Result, Section};
13
14
/// The `DebugLine` struct contains the source location to instruction mapping
15
/// found in the `.debug_line` section.
16
#[derive(Debug, Default, Clone, Copy)]
17
pub struct DebugLine<R> {
18
    debug_line_section: R,
19
}
20
21
impl<'input, Endian> DebugLine<EndianSlice<'input, Endian>>
22
where
23
    Endian: Endianity,
24
{
25
    /// Construct a new `DebugLine` instance from the data in the `.debug_line`
26
    /// section.
27
    ///
28
    /// It is the caller's responsibility to read the `.debug_line` section and
29
    /// present it as a `&[u8]` slice. That means using some ELF loader on
30
    /// Linux, a Mach-O loader on macOS, etc.
31
    ///
32
    /// ```
33
    /// use gimli::{DebugLine, LittleEndian};
34
    ///
35
    /// # let buf = [0x00, 0x01, 0x02, 0x03];
36
    /// # let read_debug_line_section_somehow = || &buf;
37
    /// let debug_line = DebugLine::new(read_debug_line_section_somehow(), LittleEndian);
38
    /// ```
39
0
    pub fn new(debug_line_section: &'input [u8], endian: Endian) -> Self {
40
0
        Self::from(EndianSlice::new(debug_line_section, endian))
41
0
    }
42
}
43
44
impl<R: Reader> DebugLine<R> {
45
    /// Parse the line number program whose header is at the given `offset` in the
46
    /// `.debug_line` section.
47
    ///
48
    /// The `address_size` must match the compilation unit that the lines apply to.
49
    /// The `comp_dir` should be from the `DW_AT_comp_dir` attribute of the compilation
50
    /// unit. The `comp_name` should be from the `DW_AT_name` attribute of the
51
    /// compilation unit.
52
    ///
53
    /// ```rust,no_run
54
    /// use gimli::{DebugLine, DebugLineOffset, IncompleteLineProgram, EndianSlice, LittleEndian};
55
    ///
56
    /// # let buf = [];
57
    /// # let read_debug_line_section_somehow = || &buf;
58
    /// let debug_line = DebugLine::new(read_debug_line_section_somehow(), LittleEndian);
59
    ///
60
    /// // In a real example, we'd grab the offset via a compilation unit
61
    /// // entry's `DW_AT_stmt_list` attribute, and the address size from that
62
    /// // unit directly.
63
    /// let offset = DebugLineOffset(0);
64
    /// let address_size = 8;
65
    ///
66
    /// let program = debug_line.program(offset, address_size, None, None)
67
    ///     .expect("should have found a header at that offset, and parsed it OK");
68
    /// ```
69
0
    pub fn program(
70
0
        &self,
71
0
        offset: DebugLineOffset<R::Offset>,
72
0
        address_size: u8,
73
0
        comp_dir: Option<R>,
74
0
        comp_name: Option<R>,
75
0
    ) -> Result<IncompleteLineProgram<R>> {
76
0
        let input = &mut self.debug_line_section.clone();
77
0
        input.skip(offset.0)?;
78
0
        let header = LineProgramHeader::parse(input, offset, address_size, comp_dir, comp_name)?;
79
0
        let program = IncompleteLineProgram { header };
80
0
        Ok(program)
81
0
    }
Unexecuted instantiation: <gimli::read::line::DebugLine<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>>::program
Unexecuted instantiation: <gimli::read::line::DebugLine<_>>::program
82
}
83
84
impl<T> DebugLine<T> {
85
    /// Create a `DebugLine` section that references the data in `self`.
86
    ///
87
    /// This is useful when `R` implements `Reader` but `T` does not.
88
    ///
89
    /// Used by `DwarfSections::borrow`.
90
0
    pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> DebugLine<R>
91
0
    where
92
0
        F: FnMut(&'a T) -> R,
93
0
    {
94
0
        borrow(&self.debug_line_section).into()
95
0
    }
96
}
97
98
impl<R> Section<R> for DebugLine<R> {
99
0
    fn id() -> SectionId {
100
0
        SectionId::DebugLine
101
0
    }
Unexecuted instantiation: <gimli::read::line::DebugLine<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>> as gimli::read::Section<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>>::id
Unexecuted instantiation: <gimli::read::line::DebugLine<_> as gimli::read::Section<_>>::id
102
103
0
    fn reader(&self) -> &R {
104
0
        &self.debug_line_section
105
0
    }
Unexecuted instantiation: <gimli::read::line::DebugLine<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>> as gimli::read::Section<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>>::reader
Unexecuted instantiation: <gimli::read::line::DebugLine<_> as gimli::read::Section<_>>::reader
106
}
107
108
impl<R> From<R> for DebugLine<R> {
109
0
    fn from(debug_line_section: R) -> Self {
110
0
        DebugLine { debug_line_section }
111
0
    }
Unexecuted instantiation: <gimli::read::line::DebugLine<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>> as core::convert::From<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>>::from
Unexecuted instantiation: <gimli::read::line::DebugLine<_> as core::convert::From<_>>::from
112
}
113
114
/// Deprecated. `LineNumberProgram` has been renamed to `LineProgram`.
115
#[deprecated(note = "LineNumberProgram has been renamed to LineProgram, use that instead.")]
116
pub type LineNumberProgram<R, Offset> = dyn LineProgram<R, Offset>;
117
118
/// A `LineProgram` provides access to a `LineProgramHeader` and
119
/// a way to add files to the files table if necessary. Gimli consumers should
120
/// never need to use or see this trait.
121
pub trait LineProgram<R, Offset = <R as Reader>::Offset>
122
where
123
    R: Reader<Offset = Offset>,
124
    Offset: ReaderOffset,
125
{
126
    /// Get a reference to the held `LineProgramHeader`.
127
    fn header(&self) -> &LineProgramHeader<R, Offset>;
128
    /// Add a file to the file table if necessary.
129
    fn add_file(&mut self, file: FileEntry<R, Offset>);
130
}
131
132
impl<R, Offset> LineProgram<R, Offset> for IncompleteLineProgram<R, Offset>
133
where
134
    R: Reader<Offset = Offset>,
135
    Offset: ReaderOffset,
136
{
137
0
    fn header(&self) -> &LineProgramHeader<R, Offset> {
138
0
        &self.header
139
0
    }
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize> as gimli::read::line::LineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::header
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<_, _> as gimli::read::line::LineProgram<_, _>>::header
140
0
    fn add_file(&mut self, file: FileEntry<R, Offset>) {
141
0
        self.header.file_names.push(file);
142
0
    }
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize> as gimli::read::line::LineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::add_file
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<_, _> as gimli::read::line::LineProgram<_, _>>::add_file
143
}
144
145
impl<'program, R, Offset> LineProgram<R, Offset> for &'program CompleteLineProgram<R, Offset>
146
where
147
    R: Reader<Offset = Offset>,
148
    Offset: ReaderOffset,
149
{
150
0
    fn header(&self) -> &LineProgramHeader<R, Offset> {
151
0
        &self.header
152
0
    }
153
0
    fn add_file(&mut self, _: FileEntry<R, Offset>) {
154
0
        // Nop. Our file table is already complete.
155
0
    }
156
}
157
158
/// Deprecated. `StateMachine` has been renamed to `LineRows`.
159
#[deprecated(note = "StateMachine has been renamed to LineRows, use that instead.")]
160
pub type StateMachine<R, Program, Offset> = LineRows<R, Program, Offset>;
161
162
/// Executes a `LineProgram` to iterate over the rows in the matrix of line number information.
163
///
164
/// "The hypothetical machine used by a consumer of the line number information
165
/// to expand the byte-coded instruction stream into a matrix of line number
166
/// information." -- Section 6.2.1
167
#[derive(Debug, Clone)]
168
pub struct LineRows<R, Program, Offset = <R as Reader>::Offset>
169
where
170
    Program: LineProgram<R, Offset>,
171
    R: Reader<Offset = Offset>,
172
    Offset: ReaderOffset,
173
{
174
    program: Program,
175
    row: LineRow,
176
    instructions: LineInstructions<R>,
177
}
178
179
type OneShotLineRows<R, Offset = <R as Reader>::Offset> =
180
    LineRows<R, IncompleteLineProgram<R, Offset>, Offset>;
181
182
type ResumedLineRows<'program, R, Offset = <R as Reader>::Offset> =
183
    LineRows<R, &'program CompleteLineProgram<R, Offset>, Offset>;
184
185
impl<R, Program, Offset> LineRows<R, Program, Offset>
186
where
187
    Program: LineProgram<R, Offset>,
188
    R: Reader<Offset = Offset>,
189
    Offset: ReaderOffset,
190
{
191
0
    fn new(program: IncompleteLineProgram<R, Offset>) -> OneShotLineRows<R, Offset> {
192
0
        let row = LineRow::new(program.header());
193
0
        let instructions = LineInstructions {
194
0
            input: program.header().program_buf.clone(),
195
0
        };
196
0
        LineRows {
197
0
            program,
198
0
            row,
199
0
            instructions,
200
0
        }
201
0
    }
Unexecuted instantiation: <gimli::read::line::LineRows<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>, usize>>::new
Unexecuted instantiation: <gimli::read::line::LineRows<_, _, _>>::new
202
203
0
    fn resume<'program>(
204
0
        program: &'program CompleteLineProgram<R, Offset>,
205
0
        sequence: &LineSequence<R>,
206
0
    ) -> ResumedLineRows<'program, R, Offset> {
207
0
        let row = LineRow::new(program.header());
208
0
        let instructions = sequence.instructions.clone();
209
0
        LineRows {
210
0
            program,
211
0
            row,
212
0
            instructions,
213
0
        }
214
0
    }
215
216
    /// Get a reference to the header for this state machine's line number
217
    /// program.
218
    #[inline]
219
0
    pub fn header(&self) -> &LineProgramHeader<R, Offset> {
220
0
        self.program.header()
221
0
    }
Unexecuted instantiation: <gimli::read::line::LineRows<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>, usize>>::header
Unexecuted instantiation: <gimli::read::line::LineRows<_, _, _>>::header
222
223
    /// Parse and execute the next instructions in the line number program until
224
    /// another row in the line number matrix is computed.
225
    ///
226
    /// The freshly computed row is returned as `Ok(Some((header, row)))`.
227
    /// If the matrix is complete, and there are no more new rows in the line
228
    /// number matrix, then `Ok(None)` is returned. If there was an error parsing
229
    /// an instruction, then `Err(e)` is returned.
230
    ///
231
    /// Unfortunately, the references mean that this cannot be a
232
    /// `FallibleIterator`.
233
0
    pub fn next_row(&mut self) -> Result<Option<(&LineProgramHeader<R, Offset>, &LineRow)>> {
234
0
        // Perform any reset that was required after copying the previous row.
235
0
        self.row.reset(self.program.header());
236
237
        loop {
238
            // Split the borrow here, rather than calling `self.header()`.
239
0
            match self.instructions.next_instruction(self.program.header()) {
240
0
                Err(err) => return Err(err),
241
0
                Ok(None) => return Ok(None),
242
0
                Ok(Some(instruction)) => {
243
0
                    if self.row.execute(instruction, &mut self.program) {
244
0
                        if self.row.tombstone {
245
0
                            // Perform any reset that was required for the tombstone row.
246
0
                            // Normally this is done when `next_row` is called again, but for
247
0
                            // tombstones we loop immediately.
248
0
                            self.row.reset(self.program.header());
249
0
                        } else {
250
0
                            return Ok(Some((self.header(), &self.row)));
251
                        }
252
0
                    }
253
                    // Fall through, parse the next instruction, and see if that
254
                    // yields a row.
255
                }
256
            }
257
        }
258
0
    }
Unexecuted instantiation: <gimli::read::line::LineRows<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>, usize>>::next_row
Unexecuted instantiation: <gimli::read::line::LineRows<_, _, _>>::next_row
259
}
260
261
/// Deprecated. `Opcode` has been renamed to `LineInstruction`.
262
#[deprecated(note = "Opcode has been renamed to LineInstruction, use that instead.")]
263
pub type Opcode<R> = LineInstruction<R, <R as Reader>::Offset>;
264
265
/// A parsed line number program instruction.
266
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267
pub enum LineInstruction<R, Offset = <R as Reader>::Offset>
268
where
269
    R: Reader<Offset = Offset>,
270
    Offset: ReaderOffset,
271
{
272
    /// > ### 6.2.5.1 Special Opcodes
273
    /// >
274
    /// > Each ubyte special opcode has the following effect on the state machine:
275
    /// >
276
    /// >   1. Add a signed integer to the line register.
277
    /// >
278
    /// >   2. Modify the operation pointer by incrementing the address and
279
    /// >   op_index registers as described below.
280
    /// >
281
    /// >   3. Append a row to the matrix using the current values of the state
282
    /// >   machine registers.
283
    /// >
284
    /// >   4. Set the basic_block register to “false.”
285
    /// >
286
    /// >   5. Set the prologue_end register to “false.”
287
    /// >
288
    /// >   6. Set the epilogue_begin register to “false.”
289
    /// >
290
    /// >   7. Set the discriminator register to 0.
291
    /// >
292
    /// > All of the special opcodes do those same seven things; they differ from
293
    /// > one another only in what values they add to the line, address and
294
    /// > op_index registers.
295
    Special(u8),
296
297
    /// "[`LineInstruction::Copy`] appends a row to the matrix using the current
298
    /// values of the state machine registers. Then it sets the discriminator
299
    /// register to 0, and sets the basic_block, prologue_end and epilogue_begin
300
    /// registers to “false.”"
301
    Copy,
302
303
    /// "The DW_LNS_advance_pc opcode takes a single unsigned LEB128 operand as
304
    /// the operation advance and modifies the address and op_index registers
305
    /// [the same as `LineInstruction::Special`]"
306
    AdvancePc(u64),
307
308
    /// "The DW_LNS_advance_line opcode takes a single signed LEB128 operand and
309
    /// adds that value to the line register of the state machine."
310
    AdvanceLine(i64),
311
312
    /// "The DW_LNS_set_file opcode takes a single unsigned LEB128 operand and
313
    /// stores it in the file register of the state machine."
314
    SetFile(u64),
315
316
    /// "The DW_LNS_set_column opcode takes a single unsigned LEB128 operand and
317
    /// stores it in the column register of the state machine."
318
    SetColumn(u64),
319
320
    /// "The DW_LNS_negate_stmt opcode takes no operands. It sets the is_stmt
321
    /// register of the state machine to the logical negation of its current
322
    /// value."
323
    NegateStatement,
324
325
    /// "The DW_LNS_set_basic_block opcode takes no operands. It sets the
326
    /// basic_block register of the state machine to “true.”"
327
    SetBasicBlock,
328
329
    /// > The DW_LNS_const_add_pc opcode takes no operands. It advances the
330
    /// > address and op_index registers by the increments corresponding to
331
    /// > special opcode 255.
332
    /// >
333
    /// > When the line number program needs to advance the address by a small
334
    /// > amount, it can use a single special opcode, which occupies a single
335
    /// > byte. When it needs to advance the address by up to twice the range of
336
    /// > the last special opcode, it can use DW_LNS_const_add_pc followed by a
337
    /// > special opcode, for a total of two bytes. Only if it needs to advance
338
    /// > the address by more than twice that range will it need to use both
339
    /// > DW_LNS_advance_pc and a special opcode, requiring three or more bytes.
340
    ConstAddPc,
341
342
    /// > The DW_LNS_fixed_advance_pc opcode takes a single uhalf (unencoded)
343
    /// > operand and adds it to the address register of the state machine and
344
    /// > sets the op_index register to 0. This is the only standard opcode whose
345
    /// > operand is not a variable length number. It also does not multiply the
346
    /// > operand by the minimum_instruction_length field of the header.
347
    FixedAddPc(u16),
348
349
    /// "[`LineInstruction::SetPrologueEnd`] sets the prologue_end register to “true”."
350
    SetPrologueEnd,
351
352
    /// "[`LineInstruction::SetEpilogueBegin`] sets the epilogue_begin register to
353
    /// “true”."
354
    SetEpilogueBegin,
355
356
    /// "The DW_LNS_set_isa opcode takes a single unsigned LEB128 operand and
357
    /// stores that value in the isa register of the state machine."
358
    SetIsa(u64),
359
360
    /// An unknown standard opcode with zero operands.
361
    UnknownStandard0(constants::DwLns),
362
363
    /// An unknown standard opcode with one operand.
364
    UnknownStandard1(constants::DwLns, u64),
365
366
    /// An unknown standard opcode with multiple operands.
367
    UnknownStandardN(constants::DwLns, R),
368
369
    /// > [`LineInstruction::EndSequence`] sets the end_sequence register of the state
370
    /// > machine to “true” and appends a row to the matrix using the current
371
    /// > values of the state-machine registers. Then it resets the registers to
372
    /// > the initial values specified above (see Section 6.2.2). Every line
373
    /// > number program sequence must end with a DW_LNE_end_sequence instruction
374
    /// > which creates a row whose address is that of the byte after the last
375
    /// > target machine instruction of the sequence.
376
    EndSequence,
377
378
    /// > The DW_LNE_set_address opcode takes a single relocatable address as an
379
    /// > operand. The size of the operand is the size of an address on the target
380
    /// > machine. It sets the address register to the value given by the
381
    /// > relocatable address and sets the op_index register to 0.
382
    /// >
383
    /// > All of the other line number program opcodes that affect the address
384
    /// > register add a delta to it. This instruction stores a relocatable value
385
    /// > into it instead.
386
    SetAddress(u64),
387
388
    /// Defines a new source file in the line number program and appends it to
389
    /// the line number program header's list of source files.
390
    DefineFile(FileEntry<R, Offset>),
391
392
    /// "The DW_LNE_set_discriminator opcode takes a single parameter, an
393
    /// unsigned LEB128 integer. It sets the discriminator register to the new
394
    /// value."
395
    SetDiscriminator(u64),
396
397
    /// An unknown extended opcode and the slice of its unparsed operands.
398
    UnknownExtended(constants::DwLne, R),
399
}
400
401
impl<R, Offset> LineInstruction<R, Offset>
402
where
403
    R: Reader<Offset = Offset>,
404
    Offset: ReaderOffset,
405
{
406
0
    fn parse<'header>(
407
0
        header: &'header LineProgramHeader<R>,
408
0
        input: &mut R,
409
0
    ) -> Result<LineInstruction<R>>
410
0
    where
411
0
        R: 'header,
412
0
    {
413
0
        let opcode = input.read_u8()?;
414
0
        if opcode == 0 {
415
0
            let length = input.read_uleb128().and_then(R::Offset::from_u64)?;
416
0
            let mut instr_rest = input.split(length)?;
417
0
            let opcode = instr_rest.read_u8()?;
418
419
0
            match constants::DwLne(opcode) {
420
0
                constants::DW_LNE_end_sequence => Ok(LineInstruction::EndSequence),
421
422
                constants::DW_LNE_set_address => {
423
0
                    let address = instr_rest.read_address(header.address_size())?;
424
0
                    Ok(LineInstruction::SetAddress(address))
425
                }
426
427
                constants::DW_LNE_define_file => {
428
0
                    if header.version() <= 4 {
429
0
                        let path_name = instr_rest.read_null_terminated_slice()?;
430
0
                        let entry = FileEntry::parse(&mut instr_rest, path_name)?;
431
0
                        Ok(LineInstruction::DefineFile(entry))
432
                    } else {
433
0
                        Ok(LineInstruction::UnknownExtended(
434
0
                            constants::DW_LNE_define_file,
435
0
                            instr_rest,
436
0
                        ))
437
                    }
438
                }
439
440
                constants::DW_LNE_set_discriminator => {
441
0
                    let discriminator = instr_rest.read_uleb128()?;
442
0
                    Ok(LineInstruction::SetDiscriminator(discriminator))
443
                }
444
445
0
                otherwise => Ok(LineInstruction::UnknownExtended(otherwise, instr_rest)),
446
            }
447
0
        } else if opcode >= header.opcode_base {
448
0
            Ok(LineInstruction::Special(opcode))
449
        } else {
450
0
            match constants::DwLns(opcode) {
451
0
                constants::DW_LNS_copy => Ok(LineInstruction::Copy),
452
453
                constants::DW_LNS_advance_pc => {
454
0
                    let advance = input.read_uleb128()?;
455
0
                    Ok(LineInstruction::AdvancePc(advance))
456
                }
457
458
                constants::DW_LNS_advance_line => {
459
0
                    let increment = input.read_sleb128()?;
460
0
                    Ok(LineInstruction::AdvanceLine(increment))
461
                }
462
463
                constants::DW_LNS_set_file => {
464
0
                    let file = input.read_uleb128()?;
465
0
                    Ok(LineInstruction::SetFile(file))
466
                }
467
468
                constants::DW_LNS_set_column => {
469
0
                    let column = input.read_uleb128()?;
470
0
                    Ok(LineInstruction::SetColumn(column))
471
                }
472
473
0
                constants::DW_LNS_negate_stmt => Ok(LineInstruction::NegateStatement),
474
475
0
                constants::DW_LNS_set_basic_block => Ok(LineInstruction::SetBasicBlock),
476
477
0
                constants::DW_LNS_const_add_pc => Ok(LineInstruction::ConstAddPc),
478
479
                constants::DW_LNS_fixed_advance_pc => {
480
0
                    let advance = input.read_u16()?;
481
0
                    Ok(LineInstruction::FixedAddPc(advance))
482
                }
483
484
0
                constants::DW_LNS_set_prologue_end => Ok(LineInstruction::SetPrologueEnd),
485
486
0
                constants::DW_LNS_set_epilogue_begin => Ok(LineInstruction::SetEpilogueBegin),
487
488
                constants::DW_LNS_set_isa => {
489
0
                    let isa = input.read_uleb128()?;
490
0
                    Ok(LineInstruction::SetIsa(isa))
491
                }
492
493
0
                otherwise => {
494
0
                    let mut opcode_lengths = header.standard_opcode_lengths().clone();
495
0
                    opcode_lengths.skip(R::Offset::from_u8(opcode - 1))?;
496
0
                    let num_args = opcode_lengths.read_u8()? as usize;
497
0
                    match num_args {
498
0
                        0 => Ok(LineInstruction::UnknownStandard0(otherwise)),
499
                        1 => {
500
0
                            let arg = input.read_uleb128()?;
501
0
                            Ok(LineInstruction::UnknownStandard1(otherwise, arg))
502
                        }
503
                        _ => {
504
0
                            let mut args = input.clone();
505
0
                            for _ in 0..num_args {
506
0
                                input.read_uleb128()?;
507
                            }
508
0
                            let len = input.offset_from(&args);
509
0
                            args.truncate(len)?;
510
0
                            Ok(LineInstruction::UnknownStandardN(otherwise, args))
511
                        }
512
                    }
513
                }
514
            }
515
        }
516
0
    }
Unexecuted instantiation: <gimli::read::line::LineInstruction<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::parse
Unexecuted instantiation: <gimli::read::line::LineInstruction<_, _>>::parse
517
}
518
519
impl<R, Offset> fmt::Display for LineInstruction<R, Offset>
520
where
521
    R: Reader<Offset = Offset>,
522
    Offset: ReaderOffset,
523
{
524
0
    fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
525
0
        match *self {
526
0
            LineInstruction::Special(opcode) => write!(f, "Special opcode {}", opcode),
527
0
            LineInstruction::Copy => write!(f, "{}", constants::DW_LNS_copy),
528
0
            LineInstruction::AdvancePc(advance) => {
529
0
                write!(f, "{} by {}", constants::DW_LNS_advance_pc, advance)
530
            }
531
0
            LineInstruction::AdvanceLine(increment) => {
532
0
                write!(f, "{} by {}", constants::DW_LNS_advance_line, increment)
533
            }
534
0
            LineInstruction::SetFile(file) => {
535
0
                write!(f, "{} to {}", constants::DW_LNS_set_file, file)
536
            }
537
0
            LineInstruction::SetColumn(column) => {
538
0
                write!(f, "{} to {}", constants::DW_LNS_set_column, column)
539
            }
540
0
            LineInstruction::NegateStatement => write!(f, "{}", constants::DW_LNS_negate_stmt),
541
0
            LineInstruction::SetBasicBlock => write!(f, "{}", constants::DW_LNS_set_basic_block),
542
0
            LineInstruction::ConstAddPc => write!(f, "{}", constants::DW_LNS_const_add_pc),
543
0
            LineInstruction::FixedAddPc(advance) => {
544
0
                write!(f, "{} by {}", constants::DW_LNS_fixed_advance_pc, advance)
545
            }
546
0
            LineInstruction::SetPrologueEnd => write!(f, "{}", constants::DW_LNS_set_prologue_end),
547
            LineInstruction::SetEpilogueBegin => {
548
0
                write!(f, "{}", constants::DW_LNS_set_epilogue_begin)
549
            }
550
0
            LineInstruction::SetIsa(isa) => write!(f, "{} to {}", constants::DW_LNS_set_isa, isa),
551
0
            LineInstruction::UnknownStandard0(opcode) => write!(f, "Unknown {}", opcode),
552
0
            LineInstruction::UnknownStandard1(opcode, arg) => {
553
0
                write!(f, "Unknown {} with operand {}", opcode, arg)
554
            }
555
0
            LineInstruction::UnknownStandardN(opcode, ref args) => {
556
0
                write!(f, "Unknown {} with operands {:?}", opcode, args)
557
            }
558
0
            LineInstruction::EndSequence => write!(f, "{}", constants::DW_LNE_end_sequence),
559
0
            LineInstruction::SetAddress(address) => {
560
0
                write!(f, "{} to {}", constants::DW_LNE_set_address, address)
561
            }
562
0
            LineInstruction::DefineFile(_) => write!(f, "{}", constants::DW_LNE_define_file),
563
0
            LineInstruction::SetDiscriminator(discr) => {
564
0
                write!(f, "{} to {}", constants::DW_LNE_set_discriminator, discr)
565
            }
566
0
            LineInstruction::UnknownExtended(opcode, _) => write!(f, "Unknown {}", opcode),
567
        }
568
0
    }
569
}
570
571
/// Deprecated. `OpcodesIter` has been renamed to `LineInstructions`.
572
#[deprecated(note = "OpcodesIter has been renamed to LineInstructions, use that instead.")]
573
pub type OpcodesIter<R> = LineInstructions<R>;
574
575
/// An iterator yielding parsed instructions.
576
///
577
/// See
578
/// [`LineProgramHeader::instructions`](./struct.LineProgramHeader.html#method.instructions)
579
/// for more details.
580
#[derive(Clone, Debug)]
581
pub struct LineInstructions<R: Reader> {
582
    input: R,
583
}
584
585
impl<R: Reader> LineInstructions<R> {
586
0
    fn remove_trailing(&self, other: &LineInstructions<R>) -> Result<LineInstructions<R>> {
587
0
        let offset = other.input.offset_from(&self.input);
588
0
        let mut input = self.input.clone();
589
0
        input.truncate(offset)?;
590
0
        Ok(LineInstructions { input })
591
0
    }
592
}
593
594
impl<R: Reader> LineInstructions<R> {
595
    /// Advance the iterator and return the next instruction.
596
    ///
597
    /// Returns the newly parsed instruction as `Ok(Some(instruction))`. Returns
598
    /// `Ok(None)` when iteration is complete and all instructions have already been
599
    /// parsed and yielded. If an error occurs while parsing the next attribute,
600
    /// then this error is returned as `Err(e)`, and all subsequent calls return
601
    /// `Ok(None)`.
602
    ///
603
    /// Unfortunately, the `header` parameter means that this cannot be a
604
    /// `FallibleIterator`.
605
    #[inline(always)]
606
0
    pub fn next_instruction(
607
0
        &mut self,
608
0
        header: &LineProgramHeader<R>,
609
0
    ) -> Result<Option<LineInstruction<R>>> {
610
0
        if self.input.is_empty() {
611
0
            return Ok(None);
612
0
        }
613
0
614
0
        match LineInstruction::parse(header, &mut self.input) {
615
0
            Ok(instruction) => Ok(Some(instruction)),
616
0
            Err(e) => {
617
0
                self.input.empty();
618
0
                Err(e)
619
            }
620
        }
621
0
    }
Unexecuted instantiation: <gimli::read::line::LineInstructions<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>>::next_instruction
Unexecuted instantiation: <gimli::read::line::LineInstructions<_>>::next_instruction
622
}
623
624
/// Deprecated. `LineNumberRow` has been renamed to `LineRow`.
625
#[deprecated(note = "LineNumberRow has been renamed to LineRow, use that instead.")]
626
pub type LineNumberRow = LineRow;
627
628
/// A row in the line number program's resulting matrix.
629
///
630
/// Each row is a copy of the registers of the state machine, as defined in section 6.2.2.
631
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
632
pub struct LineRow {
633
    tombstone: bool,
634
    address: Wrapping<u64>,
635
    op_index: Wrapping<u64>,
636
    file: u64,
637
    line: Wrapping<u64>,
638
    column: u64,
639
    is_stmt: bool,
640
    basic_block: bool,
641
    end_sequence: bool,
642
    prologue_end: bool,
643
    epilogue_begin: bool,
644
    isa: u64,
645
    discriminator: u64,
646
}
647
648
impl LineRow {
649
    /// Create a line number row in the initial state for the given program.
650
0
    pub fn new<R: Reader>(header: &LineProgramHeader<R>) -> Self {
651
0
        LineRow {
652
0
            // "At the beginning of each sequence within a line number program, the
653
0
            // state of the registers is:" -- Section 6.2.2
654
0
            tombstone: false,
655
0
            address: Wrapping(0),
656
0
            op_index: Wrapping(0),
657
0
            file: 1,
658
0
            line: Wrapping(1),
659
0
            column: 0,
660
0
            // "determined by default_is_stmt in the line number program header"
661
0
            is_stmt: header.line_encoding.default_is_stmt,
662
0
            basic_block: false,
663
0
            end_sequence: false,
664
0
            prologue_end: false,
665
0
            epilogue_begin: false,
666
0
            // "The isa value 0 specifies that the instruction set is the
667
0
            // architecturally determined default instruction set. This may be fixed
668
0
            // by the ABI, or it may be specified by other means, for example, by
669
0
            // the object file description."
670
0
            isa: 0,
671
0
            discriminator: 0,
672
0
        }
673
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::new::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: <gimli::read::line::LineRow>::new::<_>
674
675
    /// "The program-counter value corresponding to a machine instruction
676
    /// generated by the compiler."
677
    #[inline]
678
0
    pub fn address(&self) -> u64 {
679
0
        self.address.0
680
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::address
Unexecuted instantiation: <gimli::read::line::LineRow>::address
681
682
    /// > An unsigned integer representing the index of an operation within a VLIW
683
    /// > instruction. The index of the first operation is 0. For non-VLIW
684
    /// > architectures, this register will always be 0.
685
    /// >
686
    /// > The address and op_index registers, taken together, form an operation
687
    /// > pointer that can reference any individual operation with the
688
    /// > instruction stream.
689
    #[inline]
690
0
    pub fn op_index(&self) -> u64 {
691
0
        self.op_index.0
692
0
    }
693
694
    /// "An unsigned integer indicating the identity of the source file
695
    /// corresponding to a machine instruction."
696
    #[inline]
697
0
    pub fn file_index(&self) -> u64 {
698
0
        self.file
699
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::file_index
Unexecuted instantiation: <gimli::read::line::LineRow>::file_index
700
701
    /// The source file corresponding to the current machine instruction.
702
    #[inline]
703
0
    pub fn file<'header, R: Reader>(
704
0
        &self,
705
0
        header: &'header LineProgramHeader<R>,
706
0
    ) -> Option<&'header FileEntry<R>> {
707
0
        header.file(self.file)
708
0
    }
709
710
    /// "An unsigned integer indicating a source line number. Lines are numbered
711
    /// beginning at 1. The compiler may emit the value 0 in cases where an
712
    /// instruction cannot be attributed to any source line."
713
    /// Line number values of 0 are represented as `None`.
714
    #[inline]
715
0
    pub fn line(&self) -> Option<NonZeroU64> {
716
0
        NonZeroU64::new(self.line.0)
717
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::line
Unexecuted instantiation: <gimli::read::line::LineRow>::line
718
719
    /// "An unsigned integer indicating a column number within a source
720
    /// line. Columns are numbered beginning at 1. The value 0 is reserved to
721
    /// indicate that a statement begins at the “left edge” of the line."
722
    #[inline]
723
0
    pub fn column(&self) -> ColumnType {
724
0
        NonZeroU64::new(self.column)
725
0
            .map(ColumnType::Column)
726
0
            .unwrap_or(ColumnType::LeftEdge)
727
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::column
Unexecuted instantiation: <gimli::read::line::LineRow>::column
728
729
    /// "A boolean indicating that the current instruction is a recommended
730
    /// breakpoint location. A recommended breakpoint location is intended to
731
    /// “represent” a line, a statement and/or a semantically distinct subpart
732
    /// of a statement."
733
    #[inline]
734
0
    pub fn is_stmt(&self) -> bool {
735
0
        self.is_stmt
736
0
    }
737
738
    /// "A boolean indicating that the current instruction is the beginning of a
739
    /// basic block."
740
    #[inline]
741
0
    pub fn basic_block(&self) -> bool {
742
0
        self.basic_block
743
0
    }
744
745
    /// "A boolean indicating that the current address is that of the first byte
746
    /// after the end of a sequence of target machine instructions. end_sequence
747
    /// terminates a sequence of lines; therefore other information in the same
748
    /// row is not meaningful."
749
    #[inline]
750
0
    pub fn end_sequence(&self) -> bool {
751
0
        self.end_sequence
752
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::end_sequence
Unexecuted instantiation: <gimli::read::line::LineRow>::end_sequence
753
754
    /// "A boolean indicating that the current address is one (of possibly many)
755
    /// where execution should be suspended for an entry breakpoint of a
756
    /// function."
757
    #[inline]
758
0
    pub fn prologue_end(&self) -> bool {
759
0
        self.prologue_end
760
0
    }
761
762
    /// "A boolean indicating that the current address is one (of possibly many)
763
    /// where execution should be suspended for an exit breakpoint of a
764
    /// function."
765
    #[inline]
766
0
    pub fn epilogue_begin(&self) -> bool {
767
0
        self.epilogue_begin
768
0
    }
769
770
    /// Tag for the current instruction set architecture.
771
    ///
772
    /// > An unsigned integer whose value encodes the applicable instruction set
773
    /// > architecture for the current instruction.
774
    /// >
775
    /// > The encoding of instruction sets should be shared by all users of a
776
    /// > given architecture. It is recommended that this encoding be defined by
777
    /// > the ABI authoring committee for each architecture.
778
    #[inline]
779
0
    pub fn isa(&self) -> u64 {
780
0
        self.isa
781
0
    }
782
783
    /// "An unsigned integer identifying the block to which the current
784
    /// instruction belongs. Discriminator values are assigned arbitrarily by
785
    /// the DWARF producer and serve to distinguish among multiple blocks that
786
    /// may all be associated with the same source file, line, and column. Where
787
    /// only one block exists for a given source position, the discriminator
788
    /// value should be zero."
789
    #[inline]
790
0
    pub fn discriminator(&self) -> u64 {
791
0
        self.discriminator
792
0
    }
793
794
    /// Execute the given instruction, and return true if a new row in the
795
    /// line number matrix needs to be generated.
796
    ///
797
    /// Unknown opcodes are treated as no-ops.
798
    #[inline]
799
0
    pub fn execute<R, Program>(
800
0
        &mut self,
801
0
        instruction: LineInstruction<R>,
802
0
        program: &mut Program,
803
0
    ) -> bool
804
0
    where
805
0
        Program: LineProgram<R>,
806
0
        R: Reader,
807
0
    {
808
0
        match instruction {
809
0
            LineInstruction::Special(opcode) => {
810
0
                self.exec_special_opcode(opcode, program.header());
811
0
                true
812
            }
813
814
0
            LineInstruction::Copy => true,
815
816
0
            LineInstruction::AdvancePc(operation_advance) => {
817
0
                self.apply_operation_advance(operation_advance, program.header());
818
0
                false
819
            }
820
821
0
            LineInstruction::AdvanceLine(line_increment) => {
822
0
                self.apply_line_advance(line_increment);
823
0
                false
824
            }
825
826
0
            LineInstruction::SetFile(file) => {
827
0
                self.file = file;
828
0
                false
829
            }
830
831
0
            LineInstruction::SetColumn(column) => {
832
0
                self.column = column;
833
0
                false
834
            }
835
836
            LineInstruction::NegateStatement => {
837
0
                self.is_stmt = !self.is_stmt;
838
0
                false
839
            }
840
841
            LineInstruction::SetBasicBlock => {
842
0
                self.basic_block = true;
843
0
                false
844
            }
845
846
            LineInstruction::ConstAddPc => {
847
0
                let adjusted = self.adjust_opcode(255, program.header());
848
0
                let operation_advance = adjusted / program.header().line_encoding.line_range;
849
0
                self.apply_operation_advance(u64::from(operation_advance), program.header());
850
0
                false
851
            }
852
853
0
            LineInstruction::FixedAddPc(operand) => {
854
0
                self.address += Wrapping(u64::from(operand));
855
0
                self.op_index.0 = 0;
856
0
                false
857
            }
858
859
            LineInstruction::SetPrologueEnd => {
860
0
                self.prologue_end = true;
861
0
                false
862
            }
863
864
            LineInstruction::SetEpilogueBegin => {
865
0
                self.epilogue_begin = true;
866
0
                false
867
            }
868
869
0
            LineInstruction::SetIsa(isa) => {
870
0
                self.isa = isa;
871
0
                false
872
            }
873
874
            LineInstruction::EndSequence => {
875
0
                self.end_sequence = true;
876
0
                true
877
            }
878
879
0
            LineInstruction::SetAddress(address) => {
880
0
                let tombstone_address = !0 >> (64 - program.header().encoding.address_size * 8);
881
0
                self.tombstone = address == tombstone_address;
882
0
                self.address.0 = address;
883
0
                self.op_index.0 = 0;
884
0
                false
885
            }
886
887
0
            LineInstruction::DefineFile(entry) => {
888
0
                program.add_file(entry);
889
0
                false
890
            }
891
892
0
            LineInstruction::SetDiscriminator(discriminator) => {
893
0
                self.discriminator = discriminator;
894
0
                false
895
            }
896
897
            // Compatibility with future opcodes.
898
            LineInstruction::UnknownStandard0(_)
899
            | LineInstruction::UnknownStandard1(_, _)
900
            | LineInstruction::UnknownStandardN(_, _)
901
0
            | LineInstruction::UnknownExtended(_, _) => false,
902
        }
903
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::execute::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>
Unexecuted instantiation: <gimli::read::line::LineRow>::execute::<_, _>
904
905
    /// Perform any reset that was required after copying the previous row.
906
    #[inline]
907
0
    pub fn reset<R: Reader>(&mut self, header: &LineProgramHeader<R>) {
908
0
        if self.end_sequence {
909
0
            // Previous instruction was EndSequence, so reset everything
910
0
            // as specified in Section 6.2.5.3.
911
0
            *self = Self::new(header);
912
0
        } else {
913
0
            // Previous instruction was one of:
914
0
            // - Special - specified in Section 6.2.5.1, steps 4-7
915
0
            // - Copy - specified in Section 6.2.5.2
916
0
            // The reset behaviour is the same in both cases.
917
0
            self.discriminator = 0;
918
0
            self.basic_block = false;
919
0
            self.prologue_end = false;
920
0
            self.epilogue_begin = false;
921
0
        }
922
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::reset::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: <gimli::read::line::LineRow>::reset::<_>
923
924
    /// Step 1 of section 6.2.5.1
925
0
    fn apply_line_advance(&mut self, line_increment: i64) {
926
0
        if line_increment < 0 {
927
0
            let decrement = -line_increment as u64;
928
0
            if decrement <= self.line.0 {
929
0
                self.line.0 -= decrement;
930
0
            } else {
931
0
                self.line.0 = 0;
932
0
            }
933
0
        } else {
934
0
            self.line += Wrapping(line_increment as u64);
935
0
        }
936
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::apply_line_advance
Unexecuted instantiation: <gimli::read::line::LineRow>::apply_line_advance
937
938
    /// Step 2 of section 6.2.5.1
939
0
    fn apply_operation_advance<R: Reader>(
940
0
        &mut self,
941
0
        operation_advance: u64,
942
0
        header: &LineProgramHeader<R>,
943
0
    ) {
944
0
        let operation_advance = Wrapping(operation_advance);
945
0
946
0
        let minimum_instruction_length = u64::from(header.line_encoding.minimum_instruction_length);
947
0
        let minimum_instruction_length = Wrapping(minimum_instruction_length);
948
0
949
0
        let maximum_operations_per_instruction =
950
0
            u64::from(header.line_encoding.maximum_operations_per_instruction);
951
0
        let maximum_operations_per_instruction = Wrapping(maximum_operations_per_instruction);
952
0
953
0
        if maximum_operations_per_instruction.0 == 1 {
954
0
            self.address += minimum_instruction_length * operation_advance;
955
0
            self.op_index.0 = 0;
956
0
        } else {
957
0
            let op_index_with_advance = self.op_index + operation_advance;
958
0
            self.address += minimum_instruction_length
959
0
                * (op_index_with_advance / maximum_operations_per_instruction);
960
0
            self.op_index = op_index_with_advance % maximum_operations_per_instruction;
961
0
        }
962
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::apply_operation_advance::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: <gimli::read::line::LineRow>::apply_operation_advance::<_>
963
964
    #[inline]
965
0
    fn adjust_opcode<R: Reader>(&self, opcode: u8, header: &LineProgramHeader<R>) -> u8 {
966
0
        opcode - header.opcode_base
967
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::adjust_opcode::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: <gimli::read::line::LineRow>::adjust_opcode::<_>
968
969
    /// Section 6.2.5.1
970
0
    fn exec_special_opcode<R: Reader>(&mut self, opcode: u8, header: &LineProgramHeader<R>) {
971
0
        let adjusted_opcode = self.adjust_opcode(opcode, header);
972
0
973
0
        let line_range = header.line_encoding.line_range;
974
0
        let line_advance = adjusted_opcode % line_range;
975
0
        let operation_advance = adjusted_opcode / line_range;
976
0
977
0
        // Step 1
978
0
        let line_base = i64::from(header.line_encoding.line_base);
979
0
        self.apply_line_advance(line_base + i64::from(line_advance));
980
0
981
0
        // Step 2
982
0
        self.apply_operation_advance(u64::from(operation_advance), header);
983
0
    }
Unexecuted instantiation: <gimli::read::line::LineRow>::exec_special_opcode::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: <gimli::read::line::LineRow>::exec_special_opcode::<_>
984
}
985
986
/// The type of column that a row is referring to.
987
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
988
pub enum ColumnType {
989
    /// The `LeftEdge` means that the statement begins at the start of the new
990
    /// line.
991
    LeftEdge,
992
    /// A column number, whose range begins at 1.
993
    Column(NonZeroU64),
994
}
995
996
/// Deprecated. `LineNumberSequence` has been renamed to `LineSequence`.
997
#[deprecated(note = "LineNumberSequence has been renamed to LineSequence, use that instead.")]
998
pub type LineNumberSequence<R> = LineSequence<R>;
999
1000
/// A sequence within a line number program.  A sequence, as defined in section
1001
/// 6.2.5 of the standard, is a linear subset of a line number program within
1002
/// which addresses are monotonically increasing.
1003
#[derive(Clone, Debug)]
1004
pub struct LineSequence<R: Reader> {
1005
    /// The first address that is covered by this sequence within the line number
1006
    /// program.
1007
    pub start: u64,
1008
    /// The first address that is *not* covered by this sequence within the line
1009
    /// number program.
1010
    pub end: u64,
1011
    instructions: LineInstructions<R>,
1012
}
1013
1014
/// Deprecated. `LineNumberProgramHeader` has been renamed to `LineProgramHeader`.
1015
#[deprecated(
1016
    note = "LineNumberProgramHeader has been renamed to LineProgramHeader, use that instead."
1017
)]
1018
pub type LineNumberProgramHeader<R, Offset> = LineProgramHeader<R, Offset>;
1019
1020
/// A header for a line number program in the `.debug_line` section, as defined
1021
/// in section 6.2.4 of the standard.
1022
#[derive(Clone, Debug, Eq, PartialEq)]
1023
pub struct LineProgramHeader<R, Offset = <R as Reader>::Offset>
1024
where
1025
    R: Reader<Offset = Offset>,
1026
    Offset: ReaderOffset,
1027
{
1028
    encoding: Encoding,
1029
    offset: DebugLineOffset<Offset>,
1030
    unit_length: Offset,
1031
1032
    header_length: Offset,
1033
1034
    line_encoding: LineEncoding,
1035
1036
    /// "The number assigned to the first special opcode."
1037
    opcode_base: u8,
1038
1039
    /// "This array specifies the number of LEB128 operands for each of the
1040
    /// standard opcodes. The first element of the array corresponds to the
1041
    /// opcode whose value is 1, and the last element corresponds to the opcode
1042
    /// whose value is `opcode_base - 1`."
1043
    standard_opcode_lengths: R,
1044
1045
    /// "A sequence of directory entry format descriptions."
1046
    directory_entry_format: Vec<FileEntryFormat>,
1047
1048
    /// > Entries in this sequence describe each path that was searched for
1049
    /// > included source files in this compilation. (The paths include those
1050
    /// > directories specified explicitly by the user for the compiler to search
1051
    /// > and those the compiler searches without explicit direction.) Each path
1052
    /// > entry is either a full path name or is relative to the current directory
1053
    /// > of the compilation.
1054
    /// >
1055
    /// > The last entry is followed by a single null byte.
1056
    include_directories: Vec<AttributeValue<R, Offset>>,
1057
1058
    /// "A sequence of file entry format descriptions."
1059
    file_name_entry_format: Vec<FileEntryFormat>,
1060
1061
    /// "Entries in this sequence describe source files that contribute to the
1062
    /// line number information for this compilation unit or is used in other
1063
    /// contexts."
1064
    file_names: Vec<FileEntry<R, Offset>>,
1065
1066
    /// The encoded line program instructions.
1067
    program_buf: R,
1068
1069
    /// The current directory of the compilation.
1070
    comp_dir: Option<R>,
1071
1072
    /// The primary source file.
1073
    comp_file: Option<FileEntry<R, Offset>>,
1074
}
1075
1076
impl<R, Offset> LineProgramHeader<R, Offset>
1077
where
1078
    R: Reader<Offset = Offset>,
1079
    Offset: ReaderOffset,
1080
{
1081
    /// Return the offset of the line number program header in the `.debug_line` section.
1082
0
    pub fn offset(&self) -> DebugLineOffset<R::Offset> {
1083
0
        self.offset
1084
0
    }
1085
1086
    /// Return the length of the line number program and header, not including
1087
    /// the length of the encoded length itself.
1088
0
    pub fn unit_length(&self) -> R::Offset {
1089
0
        self.unit_length
1090
0
    }
1091
1092
    /// Return the encoding parameters for this header's line program.
1093
0
    pub fn encoding(&self) -> Encoding {
1094
0
        self.encoding
1095
0
    }
1096
1097
    /// Get the version of this header's line program.
1098
0
    pub fn version(&self) -> u16 {
1099
0
        self.encoding.version
1100
0
    }
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::version
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::version
1101
1102
    /// Get the length of the encoded line number program header, not including
1103
    /// the length of the encoded length itself.
1104
0
    pub fn header_length(&self) -> R::Offset {
1105
0
        self.header_length
1106
0
    }
1107
1108
    /// Get the size in bytes of a target machine address.
1109
0
    pub fn address_size(&self) -> u8 {
1110
0
        self.encoding.address_size
1111
0
    }
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::address_size
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::address_size
1112
1113
    /// Whether this line program is encoded in 64- or 32-bit DWARF.
1114
0
    pub fn format(&self) -> Format {
1115
0
        self.encoding.format
1116
0
    }
1117
1118
    /// Get the line encoding parameters for this header's line program.
1119
0
    pub fn line_encoding(&self) -> LineEncoding {
1120
0
        self.line_encoding
1121
0
    }
1122
1123
    /// Get the minimum instruction length any instruction in this header's line
1124
    /// program may have.
1125
0
    pub fn minimum_instruction_length(&self) -> u8 {
1126
0
        self.line_encoding.minimum_instruction_length
1127
0
    }
1128
1129
    /// Get the maximum number of operations each instruction in this header's
1130
    /// line program may have.
1131
0
    pub fn maximum_operations_per_instruction(&self) -> u8 {
1132
0
        self.line_encoding.maximum_operations_per_instruction
1133
0
    }
1134
1135
    /// Get the default value of the `is_stmt` register for this header's line
1136
    /// program.
1137
0
    pub fn default_is_stmt(&self) -> bool {
1138
0
        self.line_encoding.default_is_stmt
1139
0
    }
1140
1141
    /// Get the line base for this header's line program.
1142
0
    pub fn line_base(&self) -> i8 {
1143
0
        self.line_encoding.line_base
1144
0
    }
1145
1146
    /// Get the line range for this header's line program.
1147
0
    pub fn line_range(&self) -> u8 {
1148
0
        self.line_encoding.line_range
1149
0
    }
1150
1151
    /// Get opcode base for this header's line program.
1152
0
    pub fn opcode_base(&self) -> u8 {
1153
0
        self.opcode_base
1154
0
    }
1155
1156
    /// An array of `u8` that specifies the number of LEB128 operands for
1157
    /// each of the standard opcodes.
1158
0
    pub fn standard_opcode_lengths(&self) -> &R {
1159
0
        &self.standard_opcode_lengths
1160
0
    }
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::standard_opcode_lengths
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::standard_opcode_lengths
1161
1162
    /// Get the format of a directory entry.
1163
0
    pub fn directory_entry_format(&self) -> &[FileEntryFormat] {
1164
0
        &self.directory_entry_format[..]
1165
0
    }
1166
1167
    /// Get the set of include directories for this header's line program.
1168
    ///
1169
    /// For DWARF version <= 4, the compilation's current directory is not included
1170
    /// in the return value, but is implicitly considered to be in the set per spec.
1171
0
    pub fn include_directories(&self) -> &[AttributeValue<R, Offset>] {
1172
0
        &self.include_directories[..]
1173
0
    }
1174
1175
    /// The include directory with the given directory index.
1176
    ///
1177
    /// A directory index of 0 corresponds to the compilation unit directory.
1178
0
    pub fn directory(&self, directory: u64) -> Option<AttributeValue<R, Offset>> {
1179
0
        if self.encoding.version <= 4 {
1180
0
            if directory == 0 {
1181
0
                self.comp_dir.clone().map(AttributeValue::String)
1182
            } else {
1183
0
                let directory = directory as usize - 1;
1184
0
                self.include_directories.get(directory).cloned()
1185
            }
1186
        } else {
1187
0
            self.include_directories.get(directory as usize).cloned()
1188
        }
1189
0
    }
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::directory
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::directory
1190
1191
    /// Get the format of a file name entry.
1192
0
    pub fn file_name_entry_format(&self) -> &[FileEntryFormat] {
1193
0
        &self.file_name_entry_format[..]
1194
0
    }
1195
1196
    /// Return true if the file entries may have valid timestamps.
1197
    ///
1198
    /// Only returns false if we definitely know that all timestamp fields
1199
    /// are invalid.
1200
0
    pub fn file_has_timestamp(&self) -> bool {
1201
0
        self.encoding.version <= 4
1202
0
            || self
1203
0
                .file_name_entry_format
1204
0
                .iter()
1205
0
                .any(|x| x.content_type == constants::DW_LNCT_timestamp)
1206
0
    }
1207
1208
    /// Return true if the file entries may have valid sizes.
1209
    ///
1210
    /// Only returns false if we definitely know that all size fields
1211
    /// are invalid.
1212
0
    pub fn file_has_size(&self) -> bool {
1213
0
        self.encoding.version <= 4
1214
0
            || self
1215
0
                .file_name_entry_format
1216
0
                .iter()
1217
0
                .any(|x| x.content_type == constants::DW_LNCT_size)
1218
0
    }
1219
1220
    /// Return true if the file name entry format contains an MD5 field.
1221
0
    pub fn file_has_md5(&self) -> bool {
1222
0
        self.file_name_entry_format
1223
0
            .iter()
1224
0
            .any(|x| x.content_type == constants::DW_LNCT_MD5)
1225
0
    }
1226
1227
    /// Get the list of source files that appear in this header's line program.
1228
0
    pub fn file_names(&self) -> &[FileEntry<R, Offset>] {
1229
0
        &self.file_names[..]
1230
0
    }
1231
1232
    /// The source file with the given file index.
1233
    ///
1234
    /// A file index of 0 corresponds to the compilation unit file.
1235
    /// Note that a file index of 0 is invalid for DWARF version <= 4,
1236
    /// but we support it anyway.
1237
0
    pub fn file(&self, file: u64) -> Option<&FileEntry<R, Offset>> {
1238
0
        if self.encoding.version <= 4 {
1239
0
            if file == 0 {
1240
0
                self.comp_file.as_ref()
1241
            } else {
1242
0
                let file = file as usize - 1;
1243
0
                self.file_names.get(file)
1244
            }
1245
        } else {
1246
0
            self.file_names.get(file as usize)
1247
        }
1248
0
    }
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::file
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::file
1249
1250
    /// Get the raw, un-parsed `EndianSlice` containing this header's line number
1251
    /// program.
1252
    ///
1253
    /// ```
1254
    /// # fn foo() {
1255
    /// use gimli::{LineProgramHeader, EndianSlice, NativeEndian};
1256
    ///
1257
    /// fn get_line_number_program_header<'a>() -> LineProgramHeader<EndianSlice<'a, NativeEndian>> {
1258
    ///     // Get a line number program header from some offset in a
1259
    ///     // `.debug_line` section...
1260
    /// #   unimplemented!()
1261
    /// }
1262
    ///
1263
    /// let header = get_line_number_program_header();
1264
    /// let raw_program = header.raw_program_buf();
1265
    /// println!("The length of the raw program in bytes is {}", raw_program.len());
1266
    /// # }
1267
    /// ```
1268
0
    pub fn raw_program_buf(&self) -> R {
1269
0
        self.program_buf.clone()
1270
0
    }
1271
1272
    /// Iterate over the instructions in this header's line number program, parsing
1273
    /// them as we go.
1274
0
    pub fn instructions(&self) -> LineInstructions<R> {
1275
0
        LineInstructions {
1276
0
            input: self.program_buf.clone(),
1277
0
        }
1278
0
    }
1279
1280
0
    fn parse(
1281
0
        input: &mut R,
1282
0
        offset: DebugLineOffset<Offset>,
1283
0
        mut address_size: u8,
1284
0
        mut comp_dir: Option<R>,
1285
0
        comp_name: Option<R>,
1286
0
    ) -> Result<LineProgramHeader<R, Offset>> {
1287
0
        let (unit_length, format) = input.read_initial_length()?;
1288
0
        let rest = &mut input.split(unit_length)?;
1289
1290
0
        let version = rest.read_u16()?;
1291
0
        if version < 2 || version > 5 {
1292
0
            return Err(Error::UnknownVersion(u64::from(version)));
1293
0
        }
1294
0
1295
0
        if version >= 5 {
1296
0
            address_size = rest.read_u8()?;
1297
0
            let segment_selector_size = rest.read_u8()?;
1298
0
            if segment_selector_size != 0 {
1299
0
                return Err(Error::UnsupportedSegmentSize);
1300
0
            }
1301
0
        }
1302
1303
0
        let encoding = Encoding {
1304
0
            format,
1305
0
            version,
1306
0
            address_size,
1307
0
        };
1308
1309
0
        let header_length = rest.read_length(format)?;
1310
1311
0
        let mut program_buf = rest.clone();
1312
0
        program_buf.skip(header_length)?;
1313
0
        rest.truncate(header_length)?;
1314
1315
0
        let minimum_instruction_length = rest.read_u8()?;
1316
0
        if minimum_instruction_length == 0 {
1317
0
            return Err(Error::MinimumInstructionLengthZero);
1318
0
        }
1319
1320
        // This field did not exist before DWARF 4, but is specified to be 1 for
1321
        // non-VLIW architectures, which makes it a no-op.
1322
0
        let maximum_operations_per_instruction = if version >= 4 { rest.read_u8()? } else { 1 };
1323
0
        if maximum_operations_per_instruction == 0 {
1324
0
            return Err(Error::MaximumOperationsPerInstructionZero);
1325
0
        }
1326
1327
0
        let default_is_stmt = rest.read_u8()? != 0;
1328
0
        let line_base = rest.read_i8()?;
1329
0
        let line_range = rest.read_u8()?;
1330
0
        if line_range == 0 {
1331
0
            return Err(Error::LineRangeZero);
1332
0
        }
1333
0
        let line_encoding = LineEncoding {
1334
0
            minimum_instruction_length,
1335
0
            maximum_operations_per_instruction,
1336
0
            default_is_stmt,
1337
0
            line_base,
1338
0
            line_range,
1339
0
        };
1340
1341
0
        let opcode_base = rest.read_u8()?;
1342
0
        if opcode_base == 0 {
1343
0
            return Err(Error::OpcodeBaseZero);
1344
0
        }
1345
0
1346
0
        let standard_opcode_count = R::Offset::from_u8(opcode_base - 1);
1347
0
        let standard_opcode_lengths = rest.split(standard_opcode_count)?;
1348
1349
        let directory_entry_format;
1350
0
        let mut include_directories = Vec::new();
1351
0
        if version <= 4 {
1352
0
            directory_entry_format = Vec::new();
1353
            loop {
1354
0
                let directory = rest.read_null_terminated_slice()?;
1355
0
                if directory.is_empty() {
1356
0
                    break;
1357
0
                }
1358
0
                include_directories.push(AttributeValue::String(directory));
1359
            }
1360
        } else {
1361
0
            comp_dir = None;
1362
0
            directory_entry_format = FileEntryFormat::parse(rest)?;
1363
0
            let count = rest.read_uleb128()?;
1364
0
            for _ in 0..count {
1365
0
                include_directories.push(parse_directory_v5(
1366
0
                    rest,
1367
0
                    encoding,
1368
0
                    &directory_entry_format,
1369
0
                )?);
1370
            }
1371
        }
1372
1373
        let comp_file;
1374
        let file_name_entry_format;
1375
0
        let mut file_names = Vec::new();
1376
0
        if version <= 4 {
1377
0
            comp_file = comp_name.map(|name| FileEntry {
1378
0
                path_name: AttributeValue::String(name),
1379
0
                directory_index: 0,
1380
0
                timestamp: 0,
1381
0
                size: 0,
1382
0
                md5: [0; 16],
1383
0
            });
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::parse::{closure#0}
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::parse::{closure#0}
1384
0
1385
0
            file_name_entry_format = Vec::new();
1386
            loop {
1387
0
                let path_name = rest.read_null_terminated_slice()?;
1388
0
                if path_name.is_empty() {
1389
0
                    break;
1390
0
                }
1391
0
                file_names.push(FileEntry::parse(rest, path_name)?);
1392
            }
1393
        } else {
1394
0
            comp_file = None;
1395
0
            file_name_entry_format = FileEntryFormat::parse(rest)?;
1396
0
            let count = rest.read_uleb128()?;
1397
0
            for _ in 0..count {
1398
0
                file_names.push(parse_file_v5(rest, encoding, &file_name_entry_format)?);
1399
            }
1400
        }
1401
1402
0
        let header = LineProgramHeader {
1403
0
            encoding,
1404
0
            offset,
1405
0
            unit_length,
1406
0
            header_length,
1407
0
            line_encoding,
1408
0
            opcode_base,
1409
0
            standard_opcode_lengths,
1410
0
            directory_entry_format,
1411
0
            include_directories,
1412
0
            file_name_entry_format,
1413
0
            file_names,
1414
0
            program_buf,
1415
0
            comp_dir,
1416
0
            comp_file,
1417
0
        };
1418
0
        Ok(header)
1419
0
    }
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::parse
Unexecuted instantiation: <gimli::read::line::LineProgramHeader<_, _>>::parse
1420
}
1421
1422
/// Deprecated. `IncompleteLineNumberProgram` has been renamed to `IncompleteLineProgram`.
1423
#[deprecated(
1424
    note = "IncompleteLineNumberProgram has been renamed to IncompleteLineProgram, use that instead."
1425
)]
1426
pub type IncompleteLineNumberProgram<R, Offset> = IncompleteLineProgram<R, Offset>;
1427
1428
/// A line number program that has not been run to completion.
1429
#[derive(Clone, Debug, Eq, PartialEq)]
1430
pub struct IncompleteLineProgram<R, Offset = <R as Reader>::Offset>
1431
where
1432
    R: Reader<Offset = Offset>,
1433
    Offset: ReaderOffset,
1434
{
1435
    header: LineProgramHeader<R, Offset>,
1436
}
1437
1438
impl<R, Offset> IncompleteLineProgram<R, Offset>
1439
where
1440
    R: Reader<Offset = Offset>,
1441
    Offset: ReaderOffset,
1442
{
1443
    /// Retrieve the `LineProgramHeader` for this program.
1444
0
    pub fn header(&self) -> &LineProgramHeader<R, Offset> {
1445
0
        &self.header
1446
0
    }
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::header
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<_, _>>::header
1447
1448
    /// Construct a new `LineRows` for executing this program to iterate
1449
    /// over rows in the line information matrix.
1450
0
    pub fn rows(self) -> OneShotLineRows<R, Offset> {
1451
0
        OneShotLineRows::new(self)
1452
0
    }
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::rows
Unexecuted instantiation: <gimli::read::line::IncompleteLineProgram<_, _>>::rows
1453
1454
    /// Execute the line number program, completing the `IncompleteLineProgram`
1455
    /// into a `CompleteLineProgram` and producing an array of sequences within
1456
    /// the line number program that can later be used with
1457
    /// `CompleteLineProgram::resume_from`.
1458
    ///
1459
    /// ```
1460
    /// # fn foo() {
1461
    /// use gimli::{IncompleteLineProgram, EndianSlice, NativeEndian};
1462
    ///
1463
    /// fn get_line_number_program<'a>() -> IncompleteLineProgram<EndianSlice<'a, NativeEndian>> {
1464
    ///     // Get a line number program from some offset in a
1465
    ///     // `.debug_line` section...
1466
    /// #   unimplemented!()
1467
    /// }
1468
    ///
1469
    /// let program = get_line_number_program();
1470
    /// let (program, sequences) = program.sequences().unwrap();
1471
    /// println!("There are {} sequences in this line number program", sequences.len());
1472
    /// # }
1473
    /// ```
1474
    #[allow(clippy::type_complexity)]
1475
0
    pub fn sequences(self) -> Result<(CompleteLineProgram<R, Offset>, Vec<LineSequence<R>>)> {
1476
0
        let mut sequences = Vec::new();
1477
0
        let mut rows = self.rows();
1478
0
        let mut instructions = rows.instructions.clone();
1479
0
        let mut sequence_start_addr = None;
1480
        loop {
1481
            let sequence_end_addr;
1482
0
            if rows.next_row()?.is_none() {
1483
0
                break;
1484
0
            }
1485
0
1486
0
            let row = &rows.row;
1487
0
            if row.end_sequence() {
1488
0
                sequence_end_addr = row.address();
1489
0
            } else if sequence_start_addr.is_none() {
1490
0
                sequence_start_addr = Some(row.address());
1491
0
                continue;
1492
            } else {
1493
0
                continue;
1494
            }
1495
1496
            // We just finished a sequence.
1497
0
            sequences.push(LineSequence {
1498
0
                // In theory one could have multiple DW_LNE_end_sequence instructions
1499
0
                // in a row.
1500
0
                start: sequence_start_addr.unwrap_or(0),
1501
0
                end: sequence_end_addr,
1502
0
                instructions: instructions.remove_trailing(&rows.instructions)?,
1503
            });
1504
0
            sequence_start_addr = None;
1505
0
            instructions = rows.instructions.clone();
1506
        }
1507
1508
0
        let program = CompleteLineProgram {
1509
0
            header: rows.program.header,
1510
0
        };
1511
0
        Ok((program, sequences))
1512
0
    }
1513
}
1514
1515
/// Deprecated. `CompleteLineNumberProgram` has been renamed to `CompleteLineProgram`.
1516
#[deprecated(
1517
    note = "CompleteLineNumberProgram has been renamed to CompleteLineProgram, use that instead."
1518
)]
1519
pub type CompleteLineNumberProgram<R, Offset> = CompleteLineProgram<R, Offset>;
1520
1521
/// A line number program that has previously been run to completion.
1522
#[derive(Clone, Debug, Eq, PartialEq)]
1523
pub struct CompleteLineProgram<R, Offset = <R as Reader>::Offset>
1524
where
1525
    R: Reader<Offset = Offset>,
1526
    Offset: ReaderOffset,
1527
{
1528
    header: LineProgramHeader<R, Offset>,
1529
}
1530
1531
impl<R, Offset> CompleteLineProgram<R, Offset>
1532
where
1533
    R: Reader<Offset = Offset>,
1534
    Offset: ReaderOffset,
1535
{
1536
    /// Retrieve the `LineProgramHeader` for this program.
1537
0
    pub fn header(&self) -> &LineProgramHeader<R, Offset> {
1538
0
        &self.header
1539
0
    }
1540
1541
    /// Construct a new `LineRows` for executing the subset of the line
1542
    /// number program identified by 'sequence' and  generating the line information
1543
    /// matrix.
1544
    ///
1545
    /// ```
1546
    /// # fn foo() {
1547
    /// use gimli::{IncompleteLineProgram, EndianSlice, NativeEndian};
1548
    ///
1549
    /// fn get_line_number_program<'a>() -> IncompleteLineProgram<EndianSlice<'a, NativeEndian>> {
1550
    ///     // Get a line number program from some offset in a
1551
    ///     // `.debug_line` section...
1552
    /// #   unimplemented!()
1553
    /// }
1554
    ///
1555
    /// let program = get_line_number_program();
1556
    /// let (program, sequences) = program.sequences().unwrap();
1557
    /// for sequence in &sequences {
1558
    ///     let mut sm = program.resume_from(sequence);
1559
    /// }
1560
    /// # }
1561
    /// ```
1562
0
    pub fn resume_from<'program>(
1563
0
        &'program self,
1564
0
        sequence: &LineSequence<R>,
1565
0
    ) -> ResumedLineRows<'program, R, Offset> {
1566
0
        ResumedLineRows::resume(self, sequence)
1567
0
    }
1568
}
1569
1570
/// An entry in the `LineProgramHeader`'s `file_names` set.
1571
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1572
pub struct FileEntry<R, Offset = <R as Reader>::Offset>
1573
where
1574
    R: Reader<Offset = Offset>,
1575
    Offset: ReaderOffset,
1576
{
1577
    path_name: AttributeValue<R, Offset>,
1578
    directory_index: u64,
1579
    timestamp: u64,
1580
    size: u64,
1581
    md5: [u8; 16],
1582
}
1583
1584
impl<R, Offset> FileEntry<R, Offset>
1585
where
1586
    R: Reader<Offset = Offset>,
1587
    Offset: ReaderOffset,
1588
{
1589
    // version 2-4
1590
0
    fn parse(input: &mut R, path_name: R) -> Result<FileEntry<R, Offset>> {
1591
0
        let directory_index = input.read_uleb128()?;
1592
0
        let timestamp = input.read_uleb128()?;
1593
0
        let size = input.read_uleb128()?;
1594
1595
0
        let entry = FileEntry {
1596
0
            path_name: AttributeValue::String(path_name),
1597
0
            directory_index,
1598
0
            timestamp,
1599
0
            size,
1600
0
            md5: [0; 16],
1601
0
        };
1602
0
1603
0
        Ok(entry)
1604
0
    }
Unexecuted instantiation: <gimli::read::line::FileEntry<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::parse
Unexecuted instantiation: <gimli::read::line::FileEntry<_, _>>::parse
1605
1606
    /// > A slice containing the full or relative path name of
1607
    /// > a source file. If the entry contains a file name or a relative path
1608
    /// > name, the file is located relative to either the compilation directory
1609
    /// > (as specified by the DW_AT_comp_dir attribute given in the compilation
1610
    /// > unit) or one of the directories in the include_directories section.
1611
0
    pub fn path_name(&self) -> AttributeValue<R, Offset> {
1612
0
        self.path_name.clone()
1613
0
    }
Unexecuted instantiation: <gimli::read::line::FileEntry<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::path_name
Unexecuted instantiation: <gimli::read::line::FileEntry<_, _>>::path_name
1614
1615
    /// > An unsigned LEB128 number representing the directory index of the
1616
    /// > directory in which the file was found.
1617
    /// >
1618
    /// > ...
1619
    /// >
1620
    /// > The directory index represents an entry in the include_directories
1621
    /// > section of the line number program header. The index is 0 if the file
1622
    /// > was found in the current directory of the compilation, 1 if it was found
1623
    /// > in the first directory in the include_directories section, and so
1624
    /// > on. The directory index is ignored for file names that represent full
1625
    /// > path names.
1626
0
    pub fn directory_index(&self) -> u64 {
1627
0
        self.directory_index
1628
0
    }
Unexecuted instantiation: <gimli::read::line::FileEntry<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::directory_index
Unexecuted instantiation: <gimli::read::line::FileEntry<_, _>>::directory_index
1629
1630
    /// Get this file's directory.
1631
    ///
1632
    /// A directory index of 0 corresponds to the compilation unit directory.
1633
0
    pub fn directory(&self, header: &LineProgramHeader<R>) -> Option<AttributeValue<R, Offset>> {
1634
0
        header.directory(self.directory_index)
1635
0
    }
Unexecuted instantiation: <gimli::read::line::FileEntry<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>, usize>>::directory
Unexecuted instantiation: <gimli::read::line::FileEntry<_, _>>::directory
1636
1637
    /// The implementation-defined time of last modification of the file,
1638
    /// or 0 if not available.
1639
0
    pub fn timestamp(&self) -> u64 {
1640
0
        self.timestamp
1641
0
    }
1642
1643
    /// "An unsigned LEB128 number representing the time of last modification of
1644
    /// the file, or 0 if not available."
1645
    // Terminology changed in DWARF version 5.
1646
    #[doc(hidden)]
1647
0
    pub fn last_modification(&self) -> u64 {
1648
0
        self.timestamp
1649
0
    }
1650
1651
    /// The size of the file in bytes, or 0 if not available.
1652
0
    pub fn size(&self) -> u64 {
1653
0
        self.size
1654
0
    }
1655
1656
    /// "An unsigned LEB128 number representing the length in bytes of the file,
1657
    /// or 0 if not available."
1658
    // Terminology changed in DWARF version 5.
1659
    #[doc(hidden)]
1660
0
    pub fn length(&self) -> u64 {
1661
0
        self.size
1662
0
    }
1663
1664
    /// A 16-byte MD5 digest of the file contents.
1665
    ///
1666
    /// Only valid if `LineProgramHeader::file_has_md5` returns `true`.
1667
0
    pub fn md5(&self) -> &[u8; 16] {
1668
0
        &self.md5
1669
0
    }
1670
}
1671
1672
/// The format of a component of an include directory or file name entry.
1673
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1674
pub struct FileEntryFormat {
1675
    /// The type of information that is represented by the component.
1676
    pub content_type: constants::DwLnct,
1677
1678
    /// The encoding form of the component value.
1679
    pub form: constants::DwForm,
1680
}
1681
1682
impl FileEntryFormat {
1683
0
    fn parse<R: Reader>(input: &mut R) -> Result<Vec<FileEntryFormat>> {
1684
0
        let format_count = input.read_u8()? as usize;
1685
0
        let mut format = Vec::with_capacity(format_count);
1686
0
        let mut path_count = 0;
1687
0
        for _ in 0..format_count {
1688
0
            let content_type = input.read_uleb128()?;
1689
0
            let content_type = if content_type > u64::from(u16::max_value()) {
1690
0
                constants::DwLnct(u16::max_value())
1691
            } else {
1692
0
                constants::DwLnct(content_type as u16)
1693
            };
1694
0
            if content_type == constants::DW_LNCT_path {
1695
0
                path_count += 1;
1696
0
            }
1697
1698
0
            let form = constants::DwForm(input.read_uleb128_u16()?);
1699
1700
0
            format.push(FileEntryFormat { content_type, form });
1701
        }
1702
0
        if path_count != 1 {
1703
0
            return Err(Error::MissingFileEntryFormatPath);
1704
0
        }
1705
0
        Ok(format)
1706
0
    }
Unexecuted instantiation: <gimli::read::line::FileEntryFormat>::parse::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: <gimli::read::line::FileEntryFormat>::parse::<_>
1707
}
1708
1709
0
fn parse_directory_v5<R: Reader>(
1710
0
    input: &mut R,
1711
0
    encoding: Encoding,
1712
0
    formats: &[FileEntryFormat],
1713
0
) -> Result<AttributeValue<R>> {
1714
0
    let mut path_name = None;
1715
1716
0
    for format in formats {
1717
0
        let value = parse_attribute(input, encoding, format.form)?;
1718
0
        if format.content_type == constants::DW_LNCT_path {
1719
0
            path_name = Some(value);
1720
0
        }
1721
    }
1722
1723
0
    Ok(path_name.unwrap())
1724
0
}
Unexecuted instantiation: gimli::read::line::parse_directory_v5::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: gimli::read::line::parse_directory_v5::<_>
1725
1726
0
fn parse_file_v5<R: Reader>(
1727
0
    input: &mut R,
1728
0
    encoding: Encoding,
1729
0
    formats: &[FileEntryFormat],
1730
0
) -> Result<FileEntry<R>> {
1731
0
    let mut path_name = None;
1732
0
    let mut directory_index = 0;
1733
0
    let mut timestamp = 0;
1734
0
    let mut size = 0;
1735
0
    let mut md5 = [0; 16];
1736
1737
0
    for format in formats {
1738
0
        let value = parse_attribute(input, encoding, format.form)?;
1739
0
        match format.content_type {
1740
0
            constants::DW_LNCT_path => path_name = Some(value),
1741
            constants::DW_LNCT_directory_index => {
1742
0
                if let Some(value) = value.udata_value() {
1743
0
                    directory_index = value;
1744
0
                }
1745
            }
1746
            constants::DW_LNCT_timestamp => {
1747
0
                if let Some(value) = value.udata_value() {
1748
0
                    timestamp = value;
1749
0
                }
1750
            }
1751
            constants::DW_LNCT_size => {
1752
0
                if let Some(value) = value.udata_value() {
1753
0
                    size = value;
1754
0
                }
1755
            }
1756
            constants::DW_LNCT_MD5 => {
1757
0
                if let AttributeValue::Block(mut value) = value {
1758
0
                    if value.len().into_u64() == 16 {
1759
0
                        md5 = value.read_u8_array()?;
1760
0
                    }
1761
0
                }
1762
            }
1763
            // Ignore unknown content types.
1764
0
            _ => {}
1765
        }
1766
    }
1767
1768
0
    Ok(FileEntry {
1769
0
        path_name: path_name.unwrap(),
1770
0
        directory_index,
1771
0
        timestamp,
1772
0
        size,
1773
0
        md5,
1774
0
    })
1775
0
}
Unexecuted instantiation: gimli::read::line::parse_file_v5::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: gimli::read::line::parse_file_v5::<_>
1776
1777
// TODO: this should be shared with unit::parse_attribute(), but that is hard to do.
1778
0
fn parse_attribute<R: Reader>(
1779
0
    input: &mut R,
1780
0
    encoding: Encoding,
1781
0
    form: constants::DwForm,
1782
0
) -> Result<AttributeValue<R>> {
1783
0
    Ok(match form {
1784
        constants::DW_FORM_block1 => {
1785
0
            let len = input.read_u8().map(R::Offset::from_u8)?;
1786
0
            let block = input.split(len)?;
1787
0
            AttributeValue::Block(block)
1788
        }
1789
        constants::DW_FORM_block2 => {
1790
0
            let len = input.read_u16().map(R::Offset::from_u16)?;
1791
0
            let block = input.split(len)?;
1792
0
            AttributeValue::Block(block)
1793
        }
1794
        constants::DW_FORM_block4 => {
1795
0
            let len = input.read_u32().map(R::Offset::from_u32)?;
1796
0
            let block = input.split(len)?;
1797
0
            AttributeValue::Block(block)
1798
        }
1799
        constants::DW_FORM_block => {
1800
0
            let len = input.read_uleb128().and_then(R::Offset::from_u64)?;
1801
0
            let block = input.split(len)?;
1802
0
            AttributeValue::Block(block)
1803
        }
1804
        constants::DW_FORM_data1 => {
1805
0
            let data = input.read_u8()?;
1806
0
            AttributeValue::Data1(data)
1807
        }
1808
        constants::DW_FORM_data2 => {
1809
0
            let data = input.read_u16()?;
1810
0
            AttributeValue::Data2(data)
1811
        }
1812
        constants::DW_FORM_data4 => {
1813
0
            let data = input.read_u32()?;
1814
0
            AttributeValue::Data4(data)
1815
        }
1816
        constants::DW_FORM_data8 => {
1817
0
            let data = input.read_u64()?;
1818
0
            AttributeValue::Data8(data)
1819
        }
1820
        constants::DW_FORM_data16 => {
1821
0
            let block = input.split(R::Offset::from_u8(16))?;
1822
0
            AttributeValue::Block(block)
1823
        }
1824
        constants::DW_FORM_udata => {
1825
0
            let data = input.read_uleb128()?;
1826
0
            AttributeValue::Udata(data)
1827
        }
1828
        constants::DW_FORM_sdata => {
1829
0
            let data = input.read_sleb128()?;
1830
0
            AttributeValue::Sdata(data)
1831
        }
1832
        constants::DW_FORM_flag => {
1833
0
            let present = input.read_u8()?;
1834
0
            AttributeValue::Flag(present != 0)
1835
        }
1836
        constants::DW_FORM_sec_offset => {
1837
0
            let offset = input.read_offset(encoding.format)?;
1838
0
            AttributeValue::SecOffset(offset)
1839
        }
1840
        constants::DW_FORM_string => {
1841
0
            let string = input.read_null_terminated_slice()?;
1842
0
            AttributeValue::String(string)
1843
        }
1844
        constants::DW_FORM_strp => {
1845
0
            let offset = input.read_offset(encoding.format)?;
1846
0
            AttributeValue::DebugStrRef(DebugStrOffset(offset))
1847
        }
1848
        constants::DW_FORM_strp_sup | constants::DW_FORM_GNU_strp_alt => {
1849
0
            let offset = input.read_offset(encoding.format)?;
1850
0
            AttributeValue::DebugStrRefSup(DebugStrOffset(offset))
1851
        }
1852
        constants::DW_FORM_line_strp => {
1853
0
            let offset = input.read_offset(encoding.format)?;
1854
0
            AttributeValue::DebugLineStrRef(DebugLineStrOffset(offset))
1855
        }
1856
        constants::DW_FORM_strx | constants::DW_FORM_GNU_str_index => {
1857
0
            let index = input.read_uleb128().and_then(R::Offset::from_u64)?;
1858
0
            AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
1859
        }
1860
        constants::DW_FORM_strx1 => {
1861
0
            let index = input.read_u8().map(R::Offset::from_u8)?;
1862
0
            AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
1863
        }
1864
        constants::DW_FORM_strx2 => {
1865
0
            let index = input.read_u16().map(R::Offset::from_u16)?;
1866
0
            AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
1867
        }
1868
        constants::DW_FORM_strx3 => {
1869
0
            let index = input.read_uint(3).and_then(R::Offset::from_u64)?;
1870
0
            AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
1871
        }
1872
        constants::DW_FORM_strx4 => {
1873
0
            let index = input.read_u32().map(R::Offset::from_u32)?;
1874
0
            AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
1875
        }
1876
        _ => {
1877
0
            return Err(Error::UnknownForm);
1878
        }
1879
    })
1880
0
}
Unexecuted instantiation: gimli::read::line::parse_attribute::<gimli::read::endian_slice::EndianSlice<gimli::endianity::LittleEndian>>
Unexecuted instantiation: gimli::read::line::parse_attribute::<_>
1881
1882
#[cfg(test)]
1883
mod tests {
1884
    use super::*;
1885
    use crate::constants;
1886
    use crate::endianity::LittleEndian;
1887
    use crate::read::{EndianSlice, Error};
1888
    use crate::test_util::GimliSectionMethods;
1889
    use core::u64;
1890
    use core::u8;
1891
    use test_assembler::{Endian, Label, LabelMaker, Section};
1892
1893
    #[test]
1894
    fn test_parse_debug_line_32_ok() {
1895
        #[rustfmt::skip]
1896
        let buf = [
1897
            // 32-bit length = 62.
1898
            0x3e, 0x00, 0x00, 0x00,
1899
            // Version.
1900
            0x04, 0x00,
1901
            // Header length = 40.
1902
            0x28, 0x00, 0x00, 0x00,
1903
            // Minimum instruction length.
1904
            0x01,
1905
            // Maximum operations per byte.
1906
            0x01,
1907
            // Default is_stmt.
1908
            0x01,
1909
            // Line base.
1910
            0x00,
1911
            // Line range.
1912
            0x01,
1913
            // Opcode base.
1914
            0x03,
1915
            // Standard opcode lengths for opcodes 1 .. opcode base - 1.
1916
            0x01, 0x02,
1917
            // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0'
1918
            0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
1919
            // File names
1920
                // foo.rs
1921
                0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
1922
                0x00,
1923
                0x00,
1924
                0x00,
1925
                // bar.h
1926
                0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
1927
                0x01,
1928
                0x00,
1929
                0x00,
1930
            // End file names.
1931
            0x00,
1932
1933
            // Dummy line program data.
1934
            0x00, 0x00, 0x00, 0x00,
1935
            0x00, 0x00, 0x00, 0x00,
1936
            0x00, 0x00, 0x00, 0x00,
1937
            0x00, 0x00, 0x00, 0x00,
1938
1939
            // Dummy next line program.
1940
            0x00, 0x00, 0x00, 0x00,
1941
            0x00, 0x00, 0x00, 0x00,
1942
            0x00, 0x00, 0x00, 0x00,
1943
            0x00, 0x00, 0x00, 0x00,
1944
        ];
1945
1946
        let rest = &mut EndianSlice::new(&buf, LittleEndian);
1947
        let comp_dir = EndianSlice::new(b"/comp_dir", LittleEndian);
1948
        let comp_name = EndianSlice::new(b"/comp_name", LittleEndian);
1949
1950
        let header =
1951
            LineProgramHeader::parse(rest, DebugLineOffset(0), 4, Some(comp_dir), Some(comp_name))
1952
                .expect("should parse header ok");
1953
1954
        assert_eq!(
1955
            *rest,
1956
            EndianSlice::new(&buf[buf.len() - 16..], LittleEndian)
1957
        );
1958
1959
        assert_eq!(header.offset, DebugLineOffset(0));
1960
        assert_eq!(header.version(), 4);
1961
        assert_eq!(header.minimum_instruction_length(), 1);
1962
        assert_eq!(header.maximum_operations_per_instruction(), 1);
1963
        assert!(header.default_is_stmt());
1964
        assert_eq!(header.line_base(), 0);
1965
        assert_eq!(header.line_range(), 1);
1966
        assert_eq!(header.opcode_base(), 3);
1967
        assert_eq!(header.directory(0), Some(AttributeValue::String(comp_dir)));
1968
        assert_eq!(
1969
            header.file(0).unwrap().path_name,
1970
            AttributeValue::String(comp_name)
1971
        );
1972
1973
        let expected_lengths = [1, 2];
1974
        assert_eq!(header.standard_opcode_lengths().slice(), &expected_lengths);
1975
1976
        let expected_include_directories = [
1977
            AttributeValue::String(EndianSlice::new(b"/inc", LittleEndian)),
1978
            AttributeValue::String(EndianSlice::new(b"/inc2", LittleEndian)),
1979
        ];
1980
        assert_eq!(header.include_directories(), &expected_include_directories);
1981
1982
        let expected_file_names = [
1983
            FileEntry {
1984
                path_name: AttributeValue::String(EndianSlice::new(b"foo.rs", LittleEndian)),
1985
                directory_index: 0,
1986
                timestamp: 0,
1987
                size: 0,
1988
                md5: [0; 16],
1989
            },
1990
            FileEntry {
1991
                path_name: AttributeValue::String(EndianSlice::new(b"bar.h", LittleEndian)),
1992
                directory_index: 1,
1993
                timestamp: 0,
1994
                size: 0,
1995
                md5: [0; 16],
1996
            },
1997
        ];
1998
        assert_eq!(header.file_names(), &expected_file_names);
1999
    }
2000
2001
    #[test]
2002
    fn test_parse_debug_line_header_length_too_short() {
2003
        #[rustfmt::skip]
2004
        let buf = [
2005
            // 32-bit length = 62.
2006
            0x3e, 0x00, 0x00, 0x00,
2007
            // Version.
2008
            0x04, 0x00,
2009
            // Header length = 20. TOO SHORT!!!
2010
            0x15, 0x00, 0x00, 0x00,
2011
            // Minimum instruction length.
2012
            0x01,
2013
            // Maximum operations per byte.
2014
            0x01,
2015
            // Default is_stmt.
2016
            0x01,
2017
            // Line base.
2018
            0x00,
2019
            // Line range.
2020
            0x01,
2021
            // Opcode base.
2022
            0x03,
2023
            // Standard opcode lengths for opcodes 1 .. opcode base - 1.
2024
            0x01, 0x02,
2025
            // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0'
2026
            0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
2027
            // File names
2028
                // foo.rs
2029
                0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
2030
                0x00,
2031
                0x00,
2032
                0x00,
2033
                // bar.h
2034
                0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
2035
                0x01,
2036
                0x00,
2037
                0x00,
2038
            // End file names.
2039
            0x00,
2040
2041
            // Dummy line program data.
2042
            0x00, 0x00, 0x00, 0x00,
2043
            0x00, 0x00, 0x00, 0x00,
2044
            0x00, 0x00, 0x00, 0x00,
2045
            0x00, 0x00, 0x00, 0x00,
2046
2047
            // Dummy next line program.
2048
            0x00, 0x00, 0x00, 0x00,
2049
            0x00, 0x00, 0x00, 0x00,
2050
            0x00, 0x00, 0x00, 0x00,
2051
            0x00, 0x00, 0x00, 0x00,
2052
        ];
2053
2054
        let input = &mut EndianSlice::new(&buf, LittleEndian);
2055
2056
        match LineProgramHeader::parse(input, DebugLineOffset(0), 4, None, None) {
2057
            Err(Error::UnexpectedEof(_)) => {}
2058
            otherwise => panic!("Unexpected result: {:?}", otherwise),
2059
        }
2060
    }
2061
2062
    #[test]
2063
    fn test_parse_debug_line_unit_length_too_short() {
2064
        #[rustfmt::skip]
2065
        let buf = [
2066
            // 32-bit length = 40. TOO SHORT!!!
2067
            0x28, 0x00, 0x00, 0x00,
2068
            // Version.
2069
            0x04, 0x00,
2070
            // Header length = 40.
2071
            0x28, 0x00, 0x00, 0x00,
2072
            // Minimum instruction length.
2073
            0x01,
2074
            // Maximum operations per byte.
2075
            0x01,
2076
            // Default is_stmt.
2077
            0x01,
2078
            // Line base.
2079
            0x00,
2080
            // Line range.
2081
            0x01,
2082
            // Opcode base.
2083
            0x03,
2084
            // Standard opcode lengths for opcodes 1 .. opcode base - 1.
2085
            0x01, 0x02,
2086
            // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0'
2087
            0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
2088
            // File names
2089
                // foo.rs
2090
                0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
2091
                0x00,
2092
                0x00,
2093
                0x00,
2094
                // bar.h
2095
                0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
2096
                0x01,
2097
                0x00,
2098
                0x00,
2099
            // End file names.
2100
            0x00,
2101
2102
            // Dummy line program data.
2103
            0x00, 0x00, 0x00, 0x00,
2104
            0x00, 0x00, 0x00, 0x00,
2105
            0x00, 0x00, 0x00, 0x00,
2106
            0x00, 0x00, 0x00, 0x00,
2107
2108
            // Dummy next line program.
2109
            0x00, 0x00, 0x00, 0x00,
2110
            0x00, 0x00, 0x00, 0x00,
2111
            0x00, 0x00, 0x00, 0x00,
2112
            0x00, 0x00, 0x00, 0x00,
2113
        ];
2114
2115
        let input = &mut EndianSlice::new(&buf, LittleEndian);
2116
2117
        match LineProgramHeader::parse(input, DebugLineOffset(0), 4, None, None) {
2118
            Err(Error::UnexpectedEof(_)) => {}
2119
            otherwise => panic!("Unexpected result: {:?}", otherwise),
2120
        }
2121
    }
2122
2123
    const OPCODE_BASE: u8 = 13;
2124
    const STANDARD_OPCODE_LENGTHS: &[u8] = &[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1];
2125
2126
    fn make_test_header(
2127
        buf: EndianSlice<LittleEndian>,
2128
    ) -> LineProgramHeader<EndianSlice<LittleEndian>> {
2129
        let encoding = Encoding {
2130
            format: Format::Dwarf32,
2131
            version: 4,
2132
            address_size: 8,
2133
        };
2134
        let line_encoding = LineEncoding {
2135
            line_base: -3,
2136
            line_range: 12,
2137
            ..Default::default()
2138
        };
2139
        LineProgramHeader {
2140
            encoding,
2141
            offset: DebugLineOffset(0),
2142
            unit_length: 1,
2143
            header_length: 1,
2144
            line_encoding,
2145
            opcode_base: OPCODE_BASE,
2146
            standard_opcode_lengths: EndianSlice::new(STANDARD_OPCODE_LENGTHS, LittleEndian),
2147
            file_names: vec![
2148
                FileEntry {
2149
                    path_name: AttributeValue::String(EndianSlice::new(b"foo.c", LittleEndian)),
2150
                    directory_index: 0,
2151
                    timestamp: 0,
2152
                    size: 0,
2153
                    md5: [0; 16],
2154
                },
2155
                FileEntry {
2156
                    path_name: AttributeValue::String(EndianSlice::new(b"bar.rs", LittleEndian)),
2157
                    directory_index: 0,
2158
                    timestamp: 0,
2159
                    size: 0,
2160
                    md5: [0; 16],
2161
                },
2162
            ],
2163
            include_directories: vec![],
2164
            directory_entry_format: vec![],
2165
            file_name_entry_format: vec![],
2166
            program_buf: buf,
2167
            comp_dir: None,
2168
            comp_file: None,
2169
        }
2170
    }
2171
2172
    fn make_test_program(
2173
        buf: EndianSlice<LittleEndian>,
2174
    ) -> IncompleteLineProgram<EndianSlice<LittleEndian>> {
2175
        IncompleteLineProgram {
2176
            header: make_test_header(buf),
2177
        }
2178
    }
2179
2180
    #[test]
2181
    fn test_parse_special_opcodes() {
2182
        for i in OPCODE_BASE..u8::MAX {
2183
            let input = [i, 0, 0, 0];
2184
            let input = EndianSlice::new(&input, LittleEndian);
2185
            let header = make_test_header(input);
2186
2187
            let mut rest = input;
2188
            let opcode =
2189
                LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
2190
2191
            assert_eq!(*rest, *input.range_from(1..));
2192
            assert_eq!(opcode, LineInstruction::Special(i));
2193
        }
2194
    }
2195
2196
    #[test]
2197
    fn test_parse_standard_opcodes() {
2198
        fn test<Operands>(
2199
            raw: constants::DwLns,
2200
            operands: Operands,
2201
            expected: LineInstruction<EndianSlice<LittleEndian>>,
2202
        ) where
2203
            Operands: AsRef<[u8]>,
2204
        {
2205
            let mut input = Vec::new();
2206
            input.push(raw.0);
2207
            input.extend_from_slice(operands.as_ref());
2208
2209
            let expected_rest = [0, 1, 2, 3, 4];
2210
            input.extend_from_slice(&expected_rest);
2211
2212
            let input = EndianSlice::new(&input, LittleEndian);
2213
            let header = make_test_header(input);
2214
2215
            let mut rest = input;
2216
            let opcode =
2217
                LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
2218
2219
            assert_eq!(opcode, expected);
2220
            assert_eq!(*rest, expected_rest);
2221
        }
2222
2223
        test(constants::DW_LNS_copy, [], LineInstruction::Copy);
2224
        test(
2225
            constants::DW_LNS_advance_pc,
2226
            [42],
2227
            LineInstruction::AdvancePc(42),
2228
        );
2229
        test(
2230
            constants::DW_LNS_advance_line,
2231
            [9],
2232
            LineInstruction::AdvanceLine(9),
2233
        );
2234
        test(constants::DW_LNS_set_file, [7], LineInstruction::SetFile(7));
2235
        test(
2236
            constants::DW_LNS_set_column,
2237
            [1],
2238
            LineInstruction::SetColumn(1),
2239
        );
2240
        test(
2241
            constants::DW_LNS_negate_stmt,
2242
            [],
2243
            LineInstruction::NegateStatement,
2244
        );
2245
        test(
2246
            constants::DW_LNS_set_basic_block,
2247
            [],
2248
            LineInstruction::SetBasicBlock,
2249
        );
2250
        test(
2251
            constants::DW_LNS_const_add_pc,
2252
            [],
2253
            LineInstruction::ConstAddPc,
2254
        );
2255
        test(
2256
            constants::DW_LNS_fixed_advance_pc,
2257
            [42, 0],
2258
            LineInstruction::FixedAddPc(42),
2259
        );
2260
        test(
2261
            constants::DW_LNS_set_prologue_end,
2262
            [],
2263
            LineInstruction::SetPrologueEnd,
2264
        );
2265
        test(
2266
            constants::DW_LNS_set_isa,
2267
            [57 + 0x80, 100],
2268
            LineInstruction::SetIsa(12857),
2269
        );
2270
    }
2271
2272
    #[test]
2273
    fn test_parse_unknown_standard_opcode_no_args() {
2274
        let input = [OPCODE_BASE, 1, 2, 3];
2275
        let input = EndianSlice::new(&input, LittleEndian);
2276
        let mut standard_opcode_lengths = Vec::new();
2277
        let mut header = make_test_header(input);
2278
        standard_opcode_lengths.extend(header.standard_opcode_lengths.slice());
2279
        standard_opcode_lengths.push(0);
2280
        header.opcode_base += 1;
2281
        header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian);
2282
2283
        let mut rest = input;
2284
        let opcode =
2285
            LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
2286
2287
        assert_eq!(
2288
            opcode,
2289
            LineInstruction::UnknownStandard0(constants::DwLns(OPCODE_BASE))
2290
        );
2291
        assert_eq!(*rest, *input.range_from(1..));
2292
    }
2293
2294
    #[test]
2295
    fn test_parse_unknown_standard_opcode_one_arg() {
2296
        let input = [OPCODE_BASE, 1, 2, 3];
2297
        let input = EndianSlice::new(&input, LittleEndian);
2298
        let mut standard_opcode_lengths = Vec::new();
2299
        let mut header = make_test_header(input);
2300
        standard_opcode_lengths.extend(header.standard_opcode_lengths.slice());
2301
        standard_opcode_lengths.push(1);
2302
        header.opcode_base += 1;
2303
        header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian);
2304
2305
        let mut rest = input;
2306
        let opcode =
2307
            LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
2308
2309
        assert_eq!(
2310
            opcode,
2311
            LineInstruction::UnknownStandard1(constants::DwLns(OPCODE_BASE), 1)
2312
        );
2313
        assert_eq!(*rest, *input.range_from(2..));
2314
    }
2315
2316
    #[test]
2317
    fn test_parse_unknown_standard_opcode_many_args() {
2318
        let input = [OPCODE_BASE, 1, 2, 3];
2319
        let input = EndianSlice::new(&input, LittleEndian);
2320
        let args = input.range_from(1..);
2321
        let mut standard_opcode_lengths = Vec::new();
2322
        let mut header = make_test_header(input);
2323
        standard_opcode_lengths.extend(header.standard_opcode_lengths.slice());
2324
        standard_opcode_lengths.push(3);
2325
        header.opcode_base += 1;
2326
        header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian);
2327
2328
        let mut rest = input;
2329
        let opcode =
2330
            LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
2331
2332
        assert_eq!(
2333
            opcode,
2334
            LineInstruction::UnknownStandardN(constants::DwLns(OPCODE_BASE), args)
2335
        );
2336
        assert_eq!(*rest, []);
2337
    }
2338
2339
    #[test]
2340
    fn test_parse_extended_opcodes() {
2341
        fn test<Operands>(
2342
            raw: constants::DwLne,
2343
            operands: Operands,
2344
            expected: LineInstruction<EndianSlice<LittleEndian>>,
2345
        ) where
2346
            Operands: AsRef<[u8]>,
2347
        {
2348
            let mut input = Vec::new();
2349
            input.push(0);
2350
2351
            let operands = operands.as_ref();
2352
            input.push(1 + operands.len() as u8);
2353
2354
            input.push(raw.0);
2355
            input.extend_from_slice(operands);
2356
2357
            let expected_rest = [0, 1, 2, 3, 4];
2358
            input.extend_from_slice(&expected_rest);
2359
2360
            let input = EndianSlice::new(&input, LittleEndian);
2361
            let header = make_test_header(input);
2362
2363
            let mut rest = input;
2364
            let opcode =
2365
                LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
2366
2367
            assert_eq!(opcode, expected);
2368
            assert_eq!(*rest, expected_rest);
2369
        }
2370
2371
        test(
2372
            constants::DW_LNE_end_sequence,
2373
            [],
2374
            LineInstruction::EndSequence,
2375
        );
2376
        test(
2377
            constants::DW_LNE_set_address,
2378
            [1, 2, 3, 4, 5, 6, 7, 8],
2379
            LineInstruction::SetAddress(578_437_695_752_307_201),
2380
        );
2381
        test(
2382
            constants::DW_LNE_set_discriminator,
2383
            [42],
2384
            LineInstruction::SetDiscriminator(42),
2385
        );
2386
2387
        let mut file = Vec::new();
2388
        // "foo.c"
2389
        let path_name = [b'f', b'o', b'o', b'.', b'c', 0];
2390
        file.extend_from_slice(&path_name);
2391
        // Directory index.
2392
        file.push(0);
2393
        // Last modification of file.
2394
        file.push(1);
2395
        // Size of file.
2396
        file.push(2);
2397
2398
        test(
2399
            constants::DW_LNE_define_file,
2400
            file,
2401
            LineInstruction::DefineFile(FileEntry {
2402
                path_name: AttributeValue::String(EndianSlice::new(b"foo.c", LittleEndian)),
2403
                directory_index: 0,
2404
                timestamp: 1,
2405
                size: 2,
2406
                md5: [0; 16],
2407
            }),
2408
        );
2409
2410
        // Unknown extended opcode.
2411
        let operands = [1, 2, 3, 4, 5, 6];
2412
        let opcode = constants::DwLne(99);
2413
        test(
2414
            opcode,
2415
            operands,
2416
            LineInstruction::UnknownExtended(opcode, EndianSlice::new(&operands, LittleEndian)),
2417
        );
2418
    }
2419
2420
    #[test]
2421
    fn test_file_entry_directory() {
2422
        let path_name = [b'f', b'o', b'o', b'.', b'r', b's', 0];
2423
2424
        let mut file = FileEntry {
2425
            path_name: AttributeValue::String(EndianSlice::new(&path_name, LittleEndian)),
2426
            directory_index: 1,
2427
            timestamp: 0,
2428
            size: 0,
2429
            md5: [0; 16],
2430
        };
2431
2432
        let mut header = make_test_header(EndianSlice::new(&[], LittleEndian));
2433
2434
        let dir = AttributeValue::String(EndianSlice::new(b"dir", LittleEndian));
2435
        header.include_directories.push(dir);
2436
2437
        assert_eq!(file.directory(&header), Some(dir));
2438
2439
        // Now test the compilation's current directory.
2440
        file.directory_index = 0;
2441
        assert_eq!(file.directory(&header), None);
2442
    }
2443
2444
    fn assert_exec_opcode<'input>(
2445
        header: LineProgramHeader<EndianSlice<'input, LittleEndian>>,
2446
        mut registers: LineRow,
2447
        opcode: LineInstruction<EndianSlice<'input, LittleEndian>>,
2448
        expected_registers: LineRow,
2449
        expect_new_row: bool,
2450
    ) {
2451
        let mut program = IncompleteLineProgram { header };
2452
        let is_new_row = registers.execute(opcode, &mut program);
2453
2454
        assert_eq!(is_new_row, expect_new_row);
2455
        assert_eq!(registers, expected_registers);
2456
    }
2457
2458
    #[test]
2459
    fn test_exec_special_noop() {
2460
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2461
2462
        let initial_registers = LineRow::new(&header);
2463
        let opcode = LineInstruction::Special(16);
2464
        let expected_registers = initial_registers;
2465
2466
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2467
    }
2468
2469
    #[test]
2470
    fn test_exec_special_negative_line_advance() {
2471
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2472
2473
        let mut initial_registers = LineRow::new(&header);
2474
        initial_registers.line.0 = 10;
2475
2476
        let opcode = LineInstruction::Special(13);
2477
2478
        let mut expected_registers = initial_registers;
2479
        expected_registers.line.0 -= 3;
2480
2481
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2482
    }
2483
2484
    #[test]
2485
    fn test_exec_special_positive_line_advance() {
2486
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2487
2488
        let initial_registers = LineRow::new(&header);
2489
2490
        let opcode = LineInstruction::Special(19);
2491
2492
        let mut expected_registers = initial_registers;
2493
        expected_registers.line.0 += 3;
2494
2495
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2496
    }
2497
2498
    #[test]
2499
    fn test_exec_special_positive_address_advance() {
2500
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2501
2502
        let initial_registers = LineRow::new(&header);
2503
2504
        let opcode = LineInstruction::Special(52);
2505
2506
        let mut expected_registers = initial_registers;
2507
        expected_registers.address.0 += 3;
2508
2509
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2510
    }
2511
2512
    #[test]
2513
    fn test_exec_special_positive_address_and_line_advance() {
2514
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2515
2516
        let initial_registers = LineRow::new(&header);
2517
2518
        let opcode = LineInstruction::Special(55);
2519
2520
        let mut expected_registers = initial_registers;
2521
        expected_registers.address.0 += 3;
2522
        expected_registers.line.0 += 3;
2523
2524
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2525
    }
2526
2527
    #[test]
2528
    fn test_exec_special_positive_address_and_negative_line_advance() {
2529
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2530
2531
        let mut initial_registers = LineRow::new(&header);
2532
        initial_registers.line.0 = 10;
2533
2534
        let opcode = LineInstruction::Special(49);
2535
2536
        let mut expected_registers = initial_registers;
2537
        expected_registers.address.0 += 3;
2538
        expected_registers.line.0 -= 3;
2539
2540
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2541
    }
2542
2543
    #[test]
2544
    fn test_exec_special_line_underflow() {
2545
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2546
2547
        let mut initial_registers = LineRow::new(&header);
2548
        initial_registers.line.0 = 2;
2549
2550
        // -3 line advance.
2551
        let opcode = LineInstruction::Special(13);
2552
2553
        let mut expected_registers = initial_registers;
2554
        // Clamp at 0. No idea if this is the best way to handle this situation
2555
        // or not...
2556
        expected_registers.line.0 = 0;
2557
2558
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2559
    }
2560
2561
    #[test]
2562
    fn test_exec_copy() {
2563
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2564
2565
        let mut initial_registers = LineRow::new(&header);
2566
        initial_registers.address.0 = 1337;
2567
        initial_registers.line.0 = 42;
2568
2569
        let opcode = LineInstruction::Copy;
2570
2571
        let expected_registers = initial_registers;
2572
2573
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2574
    }
2575
2576
    #[test]
2577
    fn test_exec_advance_pc() {
2578
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2579
        let initial_registers = LineRow::new(&header);
2580
        let opcode = LineInstruction::AdvancePc(42);
2581
2582
        let mut expected_registers = initial_registers;
2583
        expected_registers.address.0 += 42;
2584
2585
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2586
    }
2587
2588
    #[test]
2589
    fn test_exec_advance_pc_overflow() {
2590
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2591
        let opcode = LineInstruction::AdvancePc(42);
2592
2593
        let mut initial_registers = LineRow::new(&header);
2594
        initial_registers.address.0 = u64::MAX;
2595
2596
        let mut expected_registers = initial_registers;
2597
        expected_registers.address.0 = 41;
2598
2599
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2600
    }
2601
2602
    #[test]
2603
    fn test_exec_advance_line() {
2604
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2605
        let initial_registers = LineRow::new(&header);
2606
        let opcode = LineInstruction::AdvanceLine(42);
2607
2608
        let mut expected_registers = initial_registers;
2609
        expected_registers.line.0 += 42;
2610
2611
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2612
    }
2613
2614
    #[test]
2615
    fn test_exec_advance_line_overflow() {
2616
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2617
        let opcode = LineInstruction::AdvanceLine(42);
2618
2619
        let mut initial_registers = LineRow::new(&header);
2620
        initial_registers.line.0 = u64::MAX;
2621
2622
        let mut expected_registers = initial_registers;
2623
        expected_registers.line.0 = 41;
2624
2625
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2626
    }
2627
2628
    #[test]
2629
    fn test_exec_set_file_in_bounds() {
2630
        for file_idx in 1..3 {
2631
            let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2632
            let initial_registers = LineRow::new(&header);
2633
            let opcode = LineInstruction::SetFile(file_idx);
2634
2635
            let mut expected_registers = initial_registers;
2636
            expected_registers.file = file_idx;
2637
2638
            assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2639
        }
2640
    }
2641
2642
    #[test]
2643
    fn test_exec_set_file_out_of_bounds() {
2644
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2645
        let initial_registers = LineRow::new(&header);
2646
        let opcode = LineInstruction::SetFile(100);
2647
2648
        // The spec doesn't say anything about rejecting input programs
2649
        // that set the file register out of bounds of the actual number
2650
        // of files that have been defined. Instead, we cross our
2651
        // fingers and hope that one gets defined before
2652
        // `LineRow::file` gets called and handle the error at
2653
        // that time if need be.
2654
        let mut expected_registers = initial_registers;
2655
        expected_registers.file = 100;
2656
2657
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2658
    }
2659
2660
    #[test]
2661
    fn test_file_entry_file_index_out_of_bounds() {
2662
        // These indices are 1-based, so 0 is invalid. 100 is way more than the
2663
        // number of files defined in the header.
2664
        let out_of_bounds_indices = [0, 100];
2665
2666
        for file_idx in &out_of_bounds_indices[..] {
2667
            let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2668
            let mut row = LineRow::new(&header);
2669
2670
            row.file = *file_idx;
2671
2672
            assert_eq!(row.file(&header), None);
2673
        }
2674
    }
2675
2676
    #[test]
2677
    fn test_file_entry_file_index_in_bounds() {
2678
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2679
        let mut row = LineRow::new(&header);
2680
2681
        row.file = 2;
2682
2683
        assert_eq!(row.file(&header), Some(&header.file_names()[1]));
2684
    }
2685
2686
    #[test]
2687
    fn test_exec_set_column() {
2688
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2689
        let initial_registers = LineRow::new(&header);
2690
        let opcode = LineInstruction::SetColumn(42);
2691
2692
        let mut expected_registers = initial_registers;
2693
        expected_registers.column = 42;
2694
2695
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2696
    }
2697
2698
    #[test]
2699
    fn test_exec_negate_statement() {
2700
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2701
        let initial_registers = LineRow::new(&header);
2702
        let opcode = LineInstruction::NegateStatement;
2703
2704
        let mut expected_registers = initial_registers;
2705
        expected_registers.is_stmt = !initial_registers.is_stmt;
2706
2707
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2708
    }
2709
2710
    #[test]
2711
    fn test_exec_set_basic_block() {
2712
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2713
2714
        let mut initial_registers = LineRow::new(&header);
2715
        initial_registers.basic_block = false;
2716
2717
        let opcode = LineInstruction::SetBasicBlock;
2718
2719
        let mut expected_registers = initial_registers;
2720
        expected_registers.basic_block = true;
2721
2722
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2723
    }
2724
2725
    #[test]
2726
    fn test_exec_const_add_pc() {
2727
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2728
        let initial_registers = LineRow::new(&header);
2729
        let opcode = LineInstruction::ConstAddPc;
2730
2731
        let mut expected_registers = initial_registers;
2732
        expected_registers.address.0 += 20;
2733
2734
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2735
    }
2736
2737
    #[test]
2738
    fn test_exec_fixed_add_pc() {
2739
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2740
2741
        let mut initial_registers = LineRow::new(&header);
2742
        initial_registers.op_index.0 = 1;
2743
2744
        let opcode = LineInstruction::FixedAddPc(10);
2745
2746
        let mut expected_registers = initial_registers;
2747
        expected_registers.address.0 += 10;
2748
        expected_registers.op_index.0 = 0;
2749
2750
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2751
    }
2752
2753
    #[test]
2754
    fn test_exec_set_prologue_end() {
2755
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2756
2757
        let mut initial_registers = LineRow::new(&header);
2758
        initial_registers.prologue_end = false;
2759
2760
        let opcode = LineInstruction::SetPrologueEnd;
2761
2762
        let mut expected_registers = initial_registers;
2763
        expected_registers.prologue_end = true;
2764
2765
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2766
    }
2767
2768
    #[test]
2769
    fn test_exec_set_isa() {
2770
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2771
        let initial_registers = LineRow::new(&header);
2772
        let opcode = LineInstruction::SetIsa(1993);
2773
2774
        let mut expected_registers = initial_registers;
2775
        expected_registers.isa = 1993;
2776
2777
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2778
    }
2779
2780
    #[test]
2781
    fn test_exec_unknown_standard_0() {
2782
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2783
        let initial_registers = LineRow::new(&header);
2784
        let opcode = LineInstruction::UnknownStandard0(constants::DwLns(111));
2785
        let expected_registers = initial_registers;
2786
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2787
    }
2788
2789
    #[test]
2790
    fn test_exec_unknown_standard_1() {
2791
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2792
        let initial_registers = LineRow::new(&header);
2793
        let opcode = LineInstruction::UnknownStandard1(constants::DwLns(111), 2);
2794
        let expected_registers = initial_registers;
2795
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2796
    }
2797
2798
    #[test]
2799
    fn test_exec_unknown_standard_n() {
2800
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2801
        let initial_registers = LineRow::new(&header);
2802
        let opcode = LineInstruction::UnknownStandardN(
2803
            constants::DwLns(111),
2804
            EndianSlice::new(&[2, 2, 2], LittleEndian),
2805
        );
2806
        let expected_registers = initial_registers;
2807
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2808
    }
2809
2810
    #[test]
2811
    fn test_exec_end_sequence() {
2812
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2813
        let initial_registers = LineRow::new(&header);
2814
        let opcode = LineInstruction::EndSequence;
2815
2816
        let mut expected_registers = initial_registers;
2817
        expected_registers.end_sequence = true;
2818
2819
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
2820
    }
2821
2822
    #[test]
2823
    fn test_exec_set_address() {
2824
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2825
        let initial_registers = LineRow::new(&header);
2826
        let opcode = LineInstruction::SetAddress(3030);
2827
2828
        let mut expected_registers = initial_registers;
2829
        expected_registers.address.0 = 3030;
2830
2831
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2832
    }
2833
2834
    #[test]
2835
    fn test_exec_set_address_tombstone() {
2836
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2837
        let initial_registers = LineRow::new(&header);
2838
        let opcode = LineInstruction::SetAddress(!0);
2839
2840
        let mut expected_registers = initial_registers;
2841
        expected_registers.tombstone = true;
2842
        expected_registers.address.0 = !0;
2843
2844
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2845
    }
2846
2847
    #[test]
2848
    fn test_exec_define_file() {
2849
        let mut program = make_test_program(EndianSlice::new(&[], LittleEndian));
2850
        let mut row = LineRow::new(program.header());
2851
2852
        let file = FileEntry {
2853
            path_name: AttributeValue::String(EndianSlice::new(b"test.cpp", LittleEndian)),
2854
            directory_index: 0,
2855
            timestamp: 0,
2856
            size: 0,
2857
            md5: [0; 16],
2858
        };
2859
2860
        let opcode = LineInstruction::DefineFile(file);
2861
        let is_new_row = row.execute(opcode, &mut program);
2862
2863
        assert!(!is_new_row);
2864
        assert_eq!(Some(&file), program.header().file_names.last());
2865
    }
2866
2867
    #[test]
2868
    fn test_exec_set_discriminator() {
2869
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2870
        let initial_registers = LineRow::new(&header);
2871
        let opcode = LineInstruction::SetDiscriminator(9);
2872
2873
        let mut expected_registers = initial_registers;
2874
        expected_registers.discriminator = 9;
2875
2876
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2877
    }
2878
2879
    #[test]
2880
    fn test_exec_unknown_extended() {
2881
        let header = make_test_header(EndianSlice::new(&[], LittleEndian));
2882
        let initial_registers = LineRow::new(&header);
2883
        let opcode = LineInstruction::UnknownExtended(
2884
            constants::DwLne(74),
2885
            EndianSlice::new(&[], LittleEndian),
2886
        );
2887
        let expected_registers = initial_registers;
2888
        assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
2889
    }
2890
2891
    /// Ensure that `LineRows<R,P>` is covariant wrt R.
2892
    /// This only needs to compile.
2893
    #[allow(dead_code, unreachable_code, unused_variables)]
2894
    #[allow(clippy::diverging_sub_expression)]
2895
    fn test_line_rows_variance<'a, 'b>(_: &'a [u8], _: &'b [u8])
2896
    where
2897
        'a: 'b,
2898
    {
2899
        let a: &OneShotLineRows<EndianSlice<'a, LittleEndian>> = unimplemented!();
2900
        let _: &OneShotLineRows<EndianSlice<'b, LittleEndian>> = a;
2901
    }
2902
2903
    #[test]
2904
    fn test_parse_debug_line_v5_ok() {
2905
        let expected_lengths = &[1, 2];
2906
        let expected_program = &[0, 1, 2, 3, 4];
2907
        let expected_rest = &[5, 6, 7, 8, 9];
2908
        let expected_include_directories = [
2909
            AttributeValue::String(EndianSlice::new(b"dir1", LittleEndian)),
2910
            AttributeValue::String(EndianSlice::new(b"dir2", LittleEndian)),
2911
        ];
2912
        let expected_file_names = [
2913
            FileEntry {
2914
                path_name: AttributeValue::String(EndianSlice::new(b"file1", LittleEndian)),
2915
                directory_index: 0,
2916
                timestamp: 0,
2917
                size: 0,
2918
                md5: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
2919
            },
2920
            FileEntry {
2921
                path_name: AttributeValue::String(EndianSlice::new(b"file2", LittleEndian)),
2922
                directory_index: 1,
2923
                timestamp: 0,
2924
                size: 0,
2925
                md5: [
2926
                    11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2927
                ],
2928
            },
2929
        ];
2930
2931
        for format in [Format::Dwarf32, Format::Dwarf64] {
2932
            let length = Label::new();
2933
            let header_length = Label::new();
2934
            let start = Label::new();
2935
            let header_start = Label::new();
2936
            let end = Label::new();
2937
            let header_end = Label::new();
2938
            let section = Section::with_endian(Endian::Little)
2939
                .initial_length(format, &length, &start)
2940
                .D16(5)
2941
                // Address size.
2942
                .D8(4)
2943
                // Segment selector size.
2944
                .D8(0)
2945
                .word_label(format.word_size(), &header_length)
2946
                .mark(&header_start)
2947
                // Minimum instruction length.
2948
                .D8(1)
2949
                // Maximum operations per byte.
2950
                .D8(1)
2951
                // Default is_stmt.
2952
                .D8(1)
2953
                // Line base.
2954
                .D8(0)
2955
                // Line range.
2956
                .D8(1)
2957
                // Opcode base.
2958
                .D8(expected_lengths.len() as u8 + 1)
2959
                // Standard opcode lengths for opcodes 1 .. opcode base - 1.
2960
                .append_bytes(expected_lengths)
2961
                // Directory entry format count.
2962
                .D8(1)
2963
                .uleb(constants::DW_LNCT_path.0 as u64)
2964
                .uleb(constants::DW_FORM_string.0 as u64)
2965
                // Directory count.
2966
                .D8(2)
2967
                .append_bytes(b"dir1\0")
2968
                .append_bytes(b"dir2\0")
2969
                // File entry format count.
2970
                .D8(3)
2971
                .uleb(constants::DW_LNCT_path.0 as u64)
2972
                .uleb(constants::DW_FORM_string.0 as u64)
2973
                .uleb(constants::DW_LNCT_directory_index.0 as u64)
2974
                .uleb(constants::DW_FORM_data1.0 as u64)
2975
                .uleb(constants::DW_LNCT_MD5.0 as u64)
2976
                .uleb(constants::DW_FORM_data16.0 as u64)
2977
                // File count.
2978
                .D8(2)
2979
                .append_bytes(b"file1\0")
2980
                .D8(0)
2981
                .append_bytes(&expected_file_names[0].md5)
2982
                .append_bytes(b"file2\0")
2983
                .D8(1)
2984
                .append_bytes(&expected_file_names[1].md5)
2985
                .mark(&header_end)
2986
                // Dummy line program data.
2987
                .append_bytes(expected_program)
2988
                .mark(&end)
2989
                // Dummy trailing data.
2990
                .append_bytes(expected_rest);
2991
            length.set_const((&end - &start) as u64);
2992
            header_length.set_const((&header_end - &header_start) as u64);
2993
            let section = section.get_contents().unwrap();
2994
2995
            let input = &mut EndianSlice::new(&section, LittleEndian);
2996
2997
            let header = LineProgramHeader::parse(input, DebugLineOffset(0), 0, None, None)
2998
                .expect("should parse header ok");
2999
3000
            assert_eq!(header.raw_program_buf().slice(), expected_program);
3001
            assert_eq!(input.slice(), expected_rest);
3002
3003
            assert_eq!(header.offset, DebugLineOffset(0));
3004
            assert_eq!(header.version(), 5);
3005
            assert_eq!(header.address_size(), 4);
3006
            assert_eq!(header.minimum_instruction_length(), 1);
3007
            assert_eq!(header.maximum_operations_per_instruction(), 1);
3008
            assert!(header.default_is_stmt());
3009
            assert_eq!(header.line_base(), 0);
3010
            assert_eq!(header.line_range(), 1);
3011
            assert_eq!(header.opcode_base(), expected_lengths.len() as u8 + 1);
3012
            assert_eq!(header.standard_opcode_lengths().slice(), expected_lengths);
3013
            assert_eq!(
3014
                header.directory_entry_format(),
3015
                &[FileEntryFormat {
3016
                    content_type: constants::DW_LNCT_path,
3017
                    form: constants::DW_FORM_string,
3018
                }]
3019
            );
3020
            assert_eq!(header.include_directories(), expected_include_directories);
3021
            assert_eq!(header.directory(0), Some(expected_include_directories[0]));
3022
            assert_eq!(
3023
                header.file_name_entry_format(),
3024
                &[
3025
                    FileEntryFormat {
3026
                        content_type: constants::DW_LNCT_path,
3027
                        form: constants::DW_FORM_string,
3028
                    },
3029
                    FileEntryFormat {
3030
                        content_type: constants::DW_LNCT_directory_index,
3031
                        form: constants::DW_FORM_data1,
3032
                    },
3033
                    FileEntryFormat {
3034
                        content_type: constants::DW_LNCT_MD5,
3035
                        form: constants::DW_FORM_data16,
3036
                    }
3037
                ]
3038
            );
3039
            assert_eq!(header.file_names(), expected_file_names);
3040
            assert_eq!(header.file(0), Some(&expected_file_names[0]));
3041
        }
3042
    }
3043
3044
    #[test]
3045
    fn test_sequences() {
3046
        #[rustfmt::skip]
3047
        let buf = [
3048
            // 32-bit length
3049
            94, 0x00, 0x00, 0x00,
3050
            // Version.
3051
            0x04, 0x00,
3052
            // Header length = 40.
3053
            0x28, 0x00, 0x00, 0x00,
3054
            // Minimum instruction length.
3055
            0x01,
3056
            // Maximum operations per byte.
3057
            0x01,
3058
            // Default is_stmt.
3059
            0x01,
3060
            // Line base.
3061
            0x00,
3062
            // Line range.
3063
            0x01,
3064
            // Opcode base.
3065
            0x03,
3066
            // Standard opcode lengths for opcodes 1 .. opcode base - 1.
3067
            0x01, 0x02,
3068
            // Include directories = '/', 'i', 'n', 'c', '\0', '/', 'i', 'n', 'c', '2', '\0', '\0'
3069
            0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
3070
            // File names
3071
                // foo.rs
3072
                0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
3073
                0x00,
3074
                0x00,
3075
                0x00,
3076
                // bar.h
3077
                0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
3078
                0x01,
3079
                0x00,
3080
                0x00,
3081
            // End file names.
3082
            0x00,
3083
3084
            0, 5, constants::DW_LNE_set_address.0, 1, 0, 0, 0,
3085
            constants::DW_LNS_copy.0,
3086
            constants::DW_LNS_advance_pc.0, 1,
3087
            constants::DW_LNS_copy.0,
3088
            constants::DW_LNS_advance_pc.0, 2,
3089
            0, 1, constants::DW_LNE_end_sequence.0,
3090
3091
            // Tombstone
3092
            0, 5, constants::DW_LNE_set_address.0, 0xff, 0xff, 0xff, 0xff,
3093
            constants::DW_LNS_copy.0,
3094
            constants::DW_LNS_advance_pc.0, 1,
3095
            constants::DW_LNS_copy.0,
3096
            constants::DW_LNS_advance_pc.0, 2,
3097
            0, 1, constants::DW_LNE_end_sequence.0,
3098
3099
            0, 5, constants::DW_LNE_set_address.0, 11, 0, 0, 0,
3100
            constants::DW_LNS_copy.0,
3101
            constants::DW_LNS_advance_pc.0, 1,
3102
            constants::DW_LNS_copy.0,
3103
            constants::DW_LNS_advance_pc.0, 2,
3104
            0, 1, constants::DW_LNE_end_sequence.0,
3105
        ];
3106
        assert_eq!(buf[0] as usize, buf.len() - 4);
3107
3108
        let rest = &mut EndianSlice::new(&buf, LittleEndian);
3109
3110
        let header = LineProgramHeader::parse(rest, DebugLineOffset(0), 4, None, None)
3111
            .expect("should parse header ok");
3112
        let program = IncompleteLineProgram { header };
3113
3114
        let sequences = program.sequences().unwrap().1;
3115
        assert_eq!(sequences.len(), 2);
3116
        assert_eq!(sequences[0].start, 1);
3117
        assert_eq!(sequences[0].end, 4);
3118
        assert_eq!(sequences[1].start, 11);
3119
        assert_eq!(sequences[1].end, 14);
3120
    }
3121
}