-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathline.rs
3180 lines (2784 loc) · 110 KB
/
line.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use alloc::vec::Vec;
use core::num::{NonZeroU64, Wrapping};
use crate::common::{
DebugLineOffset, DebugLineStrOffset, DebugStrOffset, DebugStrOffsetsIndex, Encoding, Format,
LineEncoding, SectionId,
};
use crate::constants;
use crate::endianity::Endianity;
use crate::read::{
AttributeValue, EndianSlice, Error, Reader, ReaderAddress, ReaderOffset, Result, Section,
};
/// The `DebugLine` struct contains the source location to instruction mapping
/// found in the `.debug_line` section.
#[derive(Debug, Default, Clone, Copy)]
pub struct DebugLine<R> {
debug_line_section: R,
}
impl<'input, Endian> DebugLine<EndianSlice<'input, Endian>>
where
Endian: Endianity,
{
/// Construct a new `DebugLine` instance from the data in the `.debug_line`
/// section.
///
/// It is the caller's responsibility to read the `.debug_line` section and
/// present it as a `&[u8]` slice. That means using some ELF loader on
/// Linux, a Mach-O loader on macOS, etc.
///
/// ```
/// use gimli::{DebugLine, LittleEndian};
///
/// # let buf = [0x00, 0x01, 0x02, 0x03];
/// # let read_debug_line_section_somehow = || &buf;
/// let debug_line = DebugLine::new(read_debug_line_section_somehow(), LittleEndian);
/// ```
pub fn new(debug_line_section: &'input [u8], endian: Endian) -> Self {
Self::from(EndianSlice::new(debug_line_section, endian))
}
}
impl<R: Reader> DebugLine<R> {
/// Parse the line number program whose header is at the given `offset` in the
/// `.debug_line` section.
///
/// The `address_size` must match the compilation unit that the lines apply to.
/// The `comp_dir` should be from the `DW_AT_comp_dir` attribute of the compilation
/// unit. The `comp_name` should be from the `DW_AT_name` attribute of the
/// compilation unit.
///
/// ```rust,no_run
/// use gimli::{DebugLine, DebugLineOffset, IncompleteLineProgram, EndianSlice, LittleEndian};
///
/// # let buf = [];
/// # let read_debug_line_section_somehow = || &buf;
/// let debug_line = DebugLine::new(read_debug_line_section_somehow(), LittleEndian);
///
/// // In a real example, we'd grab the offset via a compilation unit
/// // entry's `DW_AT_stmt_list` attribute, and the address size from that
/// // unit directly.
/// let offset = DebugLineOffset(0);
/// let address_size = 8;
///
/// let program = debug_line.program(offset, address_size, None, None)
/// .expect("should have found a header at that offset, and parsed it OK");
/// ```
pub fn program(
&self,
offset: DebugLineOffset<R::Offset>,
address_size: u8,
comp_dir: Option<R>,
comp_name: Option<R>,
) -> Result<IncompleteLineProgram<R>> {
let input = &mut self.debug_line_section.clone();
input.skip(offset.0)?;
let header = LineProgramHeader::parse(input, offset, address_size, comp_dir, comp_name)?;
let program = IncompleteLineProgram { header };
Ok(program)
}
}
impl<T> DebugLine<T> {
/// Create a `DebugLine` section that references the data in `self`.
///
/// This is useful when `R` implements `Reader` but `T` does not.
///
/// Used by `DwarfSections::borrow`.
pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> DebugLine<R>
where
F: FnMut(&'a T) -> R,
{
borrow(&self.debug_line_section).into()
}
}
impl<R> Section<R> for DebugLine<R> {
fn id() -> SectionId {
SectionId::DebugLine
}
fn reader(&self) -> &R {
&self.debug_line_section
}
}
impl<R> From<R> for DebugLine<R> {
fn from(debug_line_section: R) -> Self {
DebugLine { debug_line_section }
}
}
/// Deprecated. `LineNumberProgram` has been renamed to `LineProgram`.
#[deprecated(note = "LineNumberProgram has been renamed to LineProgram, use that instead.")]
pub type LineNumberProgram<R, Offset> = dyn LineProgram<R, Offset>;
/// A `LineProgram` provides access to a `LineProgramHeader` and
/// a way to add files to the files table if necessary. Gimli consumers should
/// never need to use or see this trait.
pub trait LineProgram<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// Get a reference to the held `LineProgramHeader`.
fn header(&self) -> &LineProgramHeader<R, Offset>;
/// Add a file to the file table if necessary.
fn add_file(&mut self, file: FileEntry<R, Offset>);
}
impl<R, Offset> LineProgram<R, Offset> for IncompleteLineProgram<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn header(&self) -> &LineProgramHeader<R, Offset> {
&self.header
}
fn add_file(&mut self, file: FileEntry<R, Offset>) {
self.header.file_names.push(file);
}
}
impl<'program, R, Offset> LineProgram<R, Offset> for &'program CompleteLineProgram<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn header(&self) -> &LineProgramHeader<R, Offset> {
&self.header
}
fn add_file(&mut self, _: FileEntry<R, Offset>) {
// Nop. Our file table is already complete.
}
}
/// Deprecated. `StateMachine` has been renamed to `LineRows`.
#[deprecated(note = "StateMachine has been renamed to LineRows, use that instead.")]
pub type StateMachine<R, Program, Offset> = LineRows<R, Program, Offset>;
/// Executes a `LineProgram` to iterate over the rows in the matrix of line number information.
///
/// "The hypothetical machine used by a consumer of the line number information
/// to expand the byte-coded instruction stream into a matrix of line number
/// information." -- Section 6.2.1
#[derive(Debug, Clone)]
pub struct LineRows<R, Program, Offset = <R as Reader>::Offset>
where
Program: LineProgram<R, Offset>,
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
program: Program,
row: LineRow,
instructions: LineInstructions<R>,
}
type OneShotLineRows<R, Offset = <R as Reader>::Offset> =
LineRows<R, IncompleteLineProgram<R, Offset>, Offset>;
type ResumedLineRows<'program, R, Offset = <R as Reader>::Offset> =
LineRows<R, &'program CompleteLineProgram<R, Offset>, Offset>;
impl<R, Program, Offset> LineRows<R, Program, Offset>
where
Program: LineProgram<R, Offset>,
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn new(program: IncompleteLineProgram<R, Offset>) -> OneShotLineRows<R, Offset> {
let row = LineRow::new(program.header());
let instructions = LineInstructions {
input: program.header().program_buf.clone(),
};
LineRows {
program,
row,
instructions,
}
}
fn resume<'program>(
program: &'program CompleteLineProgram<R, Offset>,
sequence: &LineSequence<R>,
) -> ResumedLineRows<'program, R, Offset> {
let row = LineRow::new(program.header());
let instructions = sequence.instructions.clone();
LineRows {
program,
row,
instructions,
}
}
/// Get a reference to the header for this state machine's line number
/// program.
#[inline]
pub fn header(&self) -> &LineProgramHeader<R, Offset> {
self.program.header()
}
/// Parse and execute the next instructions in the line number program until
/// another row in the line number matrix is computed.
///
/// The freshly computed row is returned as `Ok(Some((header, row)))`.
/// If the matrix is complete, and there are no more new rows in the line
/// number matrix, then `Ok(None)` is returned. If there was an error parsing
/// an instruction, then `Err(e)` is returned.
///
/// Unfortunately, the references mean that this cannot be a
/// `FallibleIterator`.
pub fn next_row(&mut self) -> Result<Option<(&LineProgramHeader<R, Offset>, &LineRow)>> {
// Perform any reset that was required after copying the previous row.
self.row.reset(self.program.header());
loop {
// Split the borrow here, rather than calling `self.header()`.
match self.instructions.next_instruction(self.program.header()) {
Err(err) => return Err(err),
Ok(None) => return Ok(None),
Ok(Some(instruction)) => {
if self.row.execute(instruction, &mut self.program)? {
if self.row.tombstone {
// Perform any reset that was required for the tombstone row.
// Normally this is done when `next_row` is called again, but for
// tombstones we loop immediately.
self.row.reset(self.program.header());
} else {
return Ok(Some((self.header(), &self.row)));
}
}
// Fall through, parse the next instruction, and see if that
// yields a row.
}
}
}
}
}
/// Deprecated. `Opcode` has been renamed to `LineInstruction`.
#[deprecated(note = "Opcode has been renamed to LineInstruction, use that instead.")]
pub type Opcode<R> = LineInstruction<R, <R as Reader>::Offset>;
/// A parsed line number program instruction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineInstruction<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// > ### 6.2.5.1 Special Opcodes
/// >
/// > Each ubyte special opcode has the following effect on the state machine:
/// >
/// > 1. Add a signed integer to the line register.
/// >
/// > 2. Modify the operation pointer by incrementing the address and
/// > op_index registers as described below.
/// >
/// > 3. Append a row to the matrix using the current values of the state
/// > machine registers.
/// >
/// > 4. Set the basic_block register to “false.”
/// >
/// > 5. Set the prologue_end register to “false.”
/// >
/// > 6. Set the epilogue_begin register to “false.”
/// >
/// > 7. Set the discriminator register to 0.
/// >
/// > All of the special opcodes do those same seven things; they differ from
/// > one another only in what values they add to the line, address and
/// > op_index registers.
Special(u8),
/// "[`LineInstruction::Copy`] appends a row to the matrix using the current
/// values of the state machine registers. Then it sets the discriminator
/// register to 0, and sets the basic_block, prologue_end and epilogue_begin
/// registers to “false.”"
Copy,
/// "The DW_LNS_advance_pc opcode takes a single unsigned LEB128 operand as
/// the operation advance and modifies the address and op_index registers
/// [the same as `LineInstruction::Special`]"
AdvancePc(u64),
/// "The DW_LNS_advance_line opcode takes a single signed LEB128 operand and
/// adds that value to the line register of the state machine."
AdvanceLine(i64),
/// "The DW_LNS_set_file opcode takes a single unsigned LEB128 operand and
/// stores it in the file register of the state machine."
SetFile(u64),
/// "The DW_LNS_set_column opcode takes a single unsigned LEB128 operand and
/// stores it in the column register of the state machine."
SetColumn(u64),
/// "The DW_LNS_negate_stmt opcode takes no operands. It sets the is_stmt
/// register of the state machine to the logical negation of its current
/// value."
NegateStatement,
/// "The DW_LNS_set_basic_block opcode takes no operands. It sets the
/// basic_block register of the state machine to “true.”"
SetBasicBlock,
/// > The DW_LNS_const_add_pc opcode takes no operands. It advances the
/// > address and op_index registers by the increments corresponding to
/// > special opcode 255.
/// >
/// > When the line number program needs to advance the address by a small
/// > amount, it can use a single special opcode, which occupies a single
/// > byte. When it needs to advance the address by up to twice the range of
/// > the last special opcode, it can use DW_LNS_const_add_pc followed by a
/// > special opcode, for a total of two bytes. Only if it needs to advance
/// > the address by more than twice that range will it need to use both
/// > DW_LNS_advance_pc and a special opcode, requiring three or more bytes.
ConstAddPc,
/// > The DW_LNS_fixed_advance_pc opcode takes a single uhalf (unencoded)
/// > operand and adds it to the address register of the state machine and
/// > sets the op_index register to 0. This is the only standard opcode whose
/// > operand is not a variable length number. It also does not multiply the
/// > operand by the minimum_instruction_length field of the header.
FixedAddPc(u16),
/// "[`LineInstruction::SetPrologueEnd`] sets the prologue_end register to “true”."
SetPrologueEnd,
/// "[`LineInstruction::SetEpilogueBegin`] sets the epilogue_begin register to
/// “true”."
SetEpilogueBegin,
/// "The DW_LNS_set_isa opcode takes a single unsigned LEB128 operand and
/// stores that value in the isa register of the state machine."
SetIsa(u64),
/// An unknown standard opcode with zero operands.
UnknownStandard0(constants::DwLns),
/// An unknown standard opcode with one operand.
UnknownStandard1(constants::DwLns, u64),
/// An unknown standard opcode with multiple operands.
UnknownStandardN(constants::DwLns, R),
/// > [`LineInstruction::EndSequence`] sets the end_sequence register of the state
/// > machine to “true” and appends a row to the matrix using the current
/// > values of the state-machine registers. Then it resets the registers to
/// > the initial values specified above (see Section 6.2.2). Every line
/// > number program sequence must end with a DW_LNE_end_sequence instruction
/// > which creates a row whose address is that of the byte after the last
/// > target machine instruction of the sequence.
EndSequence,
/// > The DW_LNE_set_address opcode takes a single relocatable address as an
/// > operand. The size of the operand is the size of an address on the target
/// > machine. It sets the address register to the value given by the
/// > relocatable address and sets the op_index register to 0.
/// >
/// > All of the other line number program opcodes that affect the address
/// > register add a delta to it. This instruction stores a relocatable value
/// > into it instead.
SetAddress(u64),
/// Defines a new source file in the line number program and appends it to
/// the line number program header's list of source files.
DefineFile(FileEntry<R, Offset>),
/// "The DW_LNE_set_discriminator opcode takes a single parameter, an
/// unsigned LEB128 integer. It sets the discriminator register to the new
/// value."
SetDiscriminator(u64),
/// An unknown extended opcode and the slice of its unparsed operands.
UnknownExtended(constants::DwLne, R),
}
impl<R, Offset> LineInstruction<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn parse<'header>(
header: &'header LineProgramHeader<R>,
input: &mut R,
) -> Result<LineInstruction<R>>
where
R: 'header,
{
let opcode = input.read_u8()?;
if opcode == 0 {
let length = input.read_uleb128().and_then(R::Offset::from_u64)?;
let mut instr_rest = input.split(length)?;
let opcode = instr_rest.read_u8()?;
match constants::DwLne(opcode) {
constants::DW_LNE_end_sequence => Ok(LineInstruction::EndSequence),
constants::DW_LNE_set_address => {
let address = instr_rest.read_address(header.address_size())?;
Ok(LineInstruction::SetAddress(address))
}
constants::DW_LNE_define_file => {
if header.version() <= 4 {
let path_name = instr_rest.read_null_terminated_slice()?;
let entry = FileEntry::parse(&mut instr_rest, path_name)?;
Ok(LineInstruction::DefineFile(entry))
} else {
Ok(LineInstruction::UnknownExtended(
constants::DW_LNE_define_file,
instr_rest,
))
}
}
constants::DW_LNE_set_discriminator => {
let discriminator = instr_rest.read_uleb128()?;
Ok(LineInstruction::SetDiscriminator(discriminator))
}
otherwise => Ok(LineInstruction::UnknownExtended(otherwise, instr_rest)),
}
} else if opcode >= header.opcode_base {
Ok(LineInstruction::Special(opcode))
} else {
match constants::DwLns(opcode) {
constants::DW_LNS_copy => Ok(LineInstruction::Copy),
constants::DW_LNS_advance_pc => {
let advance = input.read_uleb128()?;
Ok(LineInstruction::AdvancePc(advance))
}
constants::DW_LNS_advance_line => {
let increment = input.read_sleb128()?;
Ok(LineInstruction::AdvanceLine(increment))
}
constants::DW_LNS_set_file => {
let file = input.read_uleb128()?;
Ok(LineInstruction::SetFile(file))
}
constants::DW_LNS_set_column => {
let column = input.read_uleb128()?;
Ok(LineInstruction::SetColumn(column))
}
constants::DW_LNS_negate_stmt => Ok(LineInstruction::NegateStatement),
constants::DW_LNS_set_basic_block => Ok(LineInstruction::SetBasicBlock),
constants::DW_LNS_const_add_pc => Ok(LineInstruction::ConstAddPc),
constants::DW_LNS_fixed_advance_pc => {
let advance = input.read_u16()?;
Ok(LineInstruction::FixedAddPc(advance))
}
constants::DW_LNS_set_prologue_end => Ok(LineInstruction::SetPrologueEnd),
constants::DW_LNS_set_epilogue_begin => Ok(LineInstruction::SetEpilogueBegin),
constants::DW_LNS_set_isa => {
let isa = input.read_uleb128()?;
Ok(LineInstruction::SetIsa(isa))
}
otherwise => {
let mut opcode_lengths = header.standard_opcode_lengths().clone();
opcode_lengths.skip(R::Offset::from_u8(opcode - 1))?;
let num_args = opcode_lengths.read_u8()? as usize;
match num_args {
0 => Ok(LineInstruction::UnknownStandard0(otherwise)),
1 => {
let arg = input.read_uleb128()?;
Ok(LineInstruction::UnknownStandard1(otherwise, arg))
}
_ => {
let mut args = input.clone();
for _ in 0..num_args {
input.read_uleb128()?;
}
let len = input.offset_from(&args);
args.truncate(len)?;
Ok(LineInstruction::UnknownStandardN(otherwise, args))
}
}
}
}
}
}
}
/// Deprecated. `OpcodesIter` has been renamed to `LineInstructions`.
#[deprecated(note = "OpcodesIter has been renamed to LineInstructions, use that instead.")]
pub type OpcodesIter<R> = LineInstructions<R>;
/// An iterator yielding parsed instructions.
///
/// See
/// [`LineProgramHeader::instructions`](./struct.LineProgramHeader.html#method.instructions)
/// for more details.
#[derive(Clone, Debug)]
pub struct LineInstructions<R: Reader> {
input: R,
}
impl<R: Reader> LineInstructions<R> {
fn remove_trailing(&self, other: &LineInstructions<R>) -> Result<LineInstructions<R>> {
let offset = other.input.offset_from(&self.input);
let mut input = self.input.clone();
input.truncate(offset)?;
Ok(LineInstructions { input })
}
}
impl<R: Reader> LineInstructions<R> {
/// Advance the iterator and return the next instruction.
///
/// Returns the newly parsed instruction as `Ok(Some(instruction))`. Returns
/// `Ok(None)` when iteration is complete and all instructions have already been
/// parsed and yielded. If an error occurs while parsing the next attribute,
/// then this error is returned as `Err(e)`, and all subsequent calls return
/// `Ok(None)`.
///
/// Unfortunately, the `header` parameter means that this cannot be a
/// `FallibleIterator`.
#[inline(always)]
pub fn next_instruction(
&mut self,
header: &LineProgramHeader<R>,
) -> Result<Option<LineInstruction<R>>> {
if self.input.is_empty() {
return Ok(None);
}
match LineInstruction::parse(header, &mut self.input) {
Ok(instruction) => Ok(Some(instruction)),
Err(e) => {
self.input.empty();
Err(e)
}
}
}
}
/// Deprecated. `LineNumberRow` has been renamed to `LineRow`.
#[deprecated(note = "LineNumberRow has been renamed to LineRow, use that instead.")]
pub type LineNumberRow = LineRow;
/// A row in the line number program's resulting matrix.
///
/// Each row is a copy of the registers of the state machine, as defined in section 6.2.2.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineRow {
tombstone: bool,
address: u64,
op_index: Wrapping<u64>,
file: u64,
line: Wrapping<u64>,
column: u64,
is_stmt: bool,
basic_block: bool,
end_sequence: bool,
prologue_end: bool,
epilogue_begin: bool,
isa: u64,
discriminator: u64,
}
impl LineRow {
/// Create a line number row in the initial state for the given program.
pub fn new<R: Reader>(header: &LineProgramHeader<R>) -> Self {
LineRow {
// "At the beginning of each sequence within a line number program, the
// state of the registers is:" -- Section 6.2.2
tombstone: false,
address: 0,
op_index: Wrapping(0),
file: 1,
line: Wrapping(1),
column: 0,
// "determined by default_is_stmt in the line number program header"
is_stmt: header.line_encoding.default_is_stmt,
basic_block: false,
end_sequence: false,
prologue_end: false,
epilogue_begin: false,
// "The isa value 0 specifies that the instruction set is the
// architecturally determined default instruction set. This may be fixed
// by the ABI, or it may be specified by other means, for example, by
// the object file description."
isa: 0,
discriminator: 0,
}
}
/// "The program-counter value corresponding to a machine instruction
/// generated by the compiler."
#[inline]
pub fn address(&self) -> u64 {
self.address
}
/// > An unsigned integer representing the index of an operation within a VLIW
/// > instruction. The index of the first operation is 0. For non-VLIW
/// > architectures, this register will always be 0.
/// >
/// > The address and op_index registers, taken together, form an operation
/// > pointer that can reference any individual operation with the
/// > instruction stream.
#[inline]
pub fn op_index(&self) -> u64 {
self.op_index.0
}
/// "An unsigned integer indicating the identity of the source file
/// corresponding to a machine instruction."
#[inline]
pub fn file_index(&self) -> u64 {
self.file
}
/// The source file corresponding to the current machine instruction.
#[inline]
pub fn file<'header, R: Reader>(
&self,
header: &'header LineProgramHeader<R>,
) -> Option<&'header FileEntry<R>> {
header.file(self.file)
}
/// "An unsigned integer indicating a source line number. Lines are numbered
/// beginning at 1. The compiler may emit the value 0 in cases where an
/// instruction cannot be attributed to any source line."
/// Line number values of 0 are represented as `None`.
#[inline]
pub fn line(&self) -> Option<NonZeroU64> {
NonZeroU64::new(self.line.0)
}
/// "An unsigned integer indicating a column number within a source
/// line. Columns are numbered beginning at 1. The value 0 is reserved to
/// indicate that a statement begins at the “left edge” of the line."
#[inline]
pub fn column(&self) -> ColumnType {
NonZeroU64::new(self.column)
.map(ColumnType::Column)
.unwrap_or(ColumnType::LeftEdge)
}
/// "A boolean indicating that the current instruction is a recommended
/// breakpoint location. A recommended breakpoint location is intended to
/// “represent” a line, a statement and/or a semantically distinct subpart
/// of a statement."
#[inline]
pub fn is_stmt(&self) -> bool {
self.is_stmt
}
/// "A boolean indicating that the current instruction is the beginning of a
/// basic block."
#[inline]
pub fn basic_block(&self) -> bool {
self.basic_block
}
/// "A boolean indicating that the current address is that of the first byte
/// after the end of a sequence of target machine instructions. end_sequence
/// terminates a sequence of lines; therefore other information in the same
/// row is not meaningful."
#[inline]
pub fn end_sequence(&self) -> bool {
self.end_sequence
}
/// "A boolean indicating that the current address is one (of possibly many)
/// where execution should be suspended for an entry breakpoint of a
/// function."
#[inline]
pub fn prologue_end(&self) -> bool {
self.prologue_end
}
/// "A boolean indicating that the current address is one (of possibly many)
/// where execution should be suspended for an exit breakpoint of a
/// function."
#[inline]
pub fn epilogue_begin(&self) -> bool {
self.epilogue_begin
}
/// Tag for the current instruction set architecture.
///
/// > An unsigned integer whose value encodes the applicable instruction set
/// > architecture for the current instruction.
/// >
/// > The encoding of instruction sets should be shared by all users of a
/// > given architecture. It is recommended that this encoding be defined by
/// > the ABI authoring committee for each architecture.
#[inline]
pub fn isa(&self) -> u64 {
self.isa
}
/// "An unsigned integer identifying the block to which the current
/// instruction belongs. Discriminator values are assigned arbitrarily by
/// the DWARF producer and serve to distinguish among multiple blocks that
/// may all be associated with the same source file, line, and column. Where
/// only one block exists for a given source position, the discriminator
/// value should be zero."
#[inline]
pub fn discriminator(&self) -> u64 {
self.discriminator
}
/// Execute the given instruction, and return true if a new row in the
/// line number matrix needs to be generated.
///
/// Unknown opcodes are treated as no-ops.
#[inline]
pub fn execute<R, Program>(
&mut self,
instruction: LineInstruction<R>,
program: &mut Program,
) -> Result<bool>
where
Program: LineProgram<R>,
R: Reader,
{
Ok(match instruction {
LineInstruction::Special(opcode) => {
self.exec_special_opcode(opcode, program.header())?;
true
}
LineInstruction::Copy => true,
LineInstruction::AdvancePc(operation_advance) => {
self.apply_operation_advance(operation_advance, program.header())?;
false
}
LineInstruction::AdvanceLine(line_increment) => {
self.apply_line_advance(line_increment);
false
}
LineInstruction::SetFile(file) => {
self.file = file;
false
}
LineInstruction::SetColumn(column) => {
self.column = column;
false
}
LineInstruction::NegateStatement => {
self.is_stmt = !self.is_stmt;
false
}
LineInstruction::SetBasicBlock => {
self.basic_block = true;
false
}
LineInstruction::ConstAddPc => {
let adjusted = self.adjust_opcode(255, program.header());
let operation_advance = adjusted / program.header().line_encoding.line_range;
self.apply_operation_advance(u64::from(operation_advance), program.header())?;
false
}
LineInstruction::FixedAddPc(operand) => {
if !self.tombstone {
let address_size = program.header().address_size();
self.address = self.address.add_sized(u64::from(operand), address_size)?;
self.op_index.0 = 0;
}
false
}
LineInstruction::SetPrologueEnd => {
self.prologue_end = true;
false
}
LineInstruction::SetEpilogueBegin => {
self.epilogue_begin = true;
false
}
LineInstruction::SetIsa(isa) => {
self.isa = isa;
false
}
LineInstruction::EndSequence => {
self.end_sequence = true;
true
}
LineInstruction::SetAddress(address) => {
let tombstone_address = !0 >> (64 - program.header().encoding.address_size * 8);
self.tombstone = address == tombstone_address;
if !self.tombstone {
if address < self.address {
return Err(Error::InvalidAddressRange);
}
self.address = address;
self.op_index.0 = 0;
}
false
}
LineInstruction::DefineFile(entry) => {
program.add_file(entry);
false
}
LineInstruction::SetDiscriminator(discriminator) => {
self.discriminator = discriminator;
false
}
// Compatibility with future opcodes.
LineInstruction::UnknownStandard0(_)
| LineInstruction::UnknownStandard1(_, _)
| LineInstruction::UnknownStandardN(_, _)
| LineInstruction::UnknownExtended(_, _) => false,
})
}
/// Perform any reset that was required after copying the previous row.
#[inline]
pub fn reset<R: Reader>(&mut self, header: &LineProgramHeader<R>) {
if self.end_sequence {
// Previous instruction was EndSequence, so reset everything
// as specified in Section 6.2.5.3.
*self = Self::new(header);
} else {
// Previous instruction was one of:
// - Special - specified in Section 6.2.5.1, steps 4-7
// - Copy - specified in Section 6.2.5.2
// The reset behaviour is the same in both cases.
self.discriminator = 0;
self.basic_block = false;
self.prologue_end = false;
self.epilogue_begin = false;
}
}
/// Step 1 of section 6.2.5.1
fn apply_line_advance(&mut self, line_increment: i64) {
if line_increment < 0 {
let decrement = -line_increment as u64;
if decrement <= self.line.0 {
self.line.0 -= decrement;
} else {
self.line.0 = 0;
}
} else {
self.line += Wrapping(line_increment as u64);
}
}
/// Step 2 of section 6.2.5.1
fn apply_operation_advance<R: Reader>(
&mut self,
operation_advance: u64,
header: &LineProgramHeader<R>,
) -> Result<()> {
if self.tombstone {
return Ok(());
}
let operation_advance = Wrapping(operation_advance);
let minimum_instruction_length = u64::from(header.line_encoding.minimum_instruction_length);
let minimum_instruction_length = Wrapping(minimum_instruction_length);
let maximum_operations_per_instruction =
u64::from(header.line_encoding.maximum_operations_per_instruction);
let maximum_operations_per_instruction = Wrapping(maximum_operations_per_instruction);
let address_advance = if maximum_operations_per_instruction.0 == 1 {
self.op_index.0 = 0;
minimum_instruction_length * operation_advance
} else {
let op_index_with_advance = self.op_index + operation_advance;
self.op_index = op_index_with_advance % maximum_operations_per_instruction;
minimum_instruction_length
* (op_index_with_advance / maximum_operations_per_instruction)
};
self.address = self
.address
.add_sized(address_advance.0, header.address_size())?;
Ok(())
}
#[inline]
fn adjust_opcode<R: Reader>(&self, opcode: u8, header: &LineProgramHeader<R>) -> u8 {
opcode - header.opcode_base
}
/// Section 6.2.5.1
fn exec_special_opcode<R: Reader>(
&mut self,
opcode: u8,
header: &LineProgramHeader<R>,
) -> Result<()> {
let adjusted_opcode = self.adjust_opcode(opcode, header);
let line_range = header.line_encoding.line_range;
let line_advance = adjusted_opcode % line_range;
let operation_advance = adjusted_opcode / line_range;
// Step 1
let line_base = i64::from(header.line_encoding.line_base);
self.apply_line_advance(line_base + i64::from(line_advance));
// Step 2
self.apply_operation_advance(u64::from(operation_advance), header)?;
Ok(())
}
}
/// The type of column that a row is referring to.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColumnType {
/// The `LeftEdge` means that the statement begins at the start of the new
/// line.
LeftEdge,
/// A column number, whose range begins at 1.
Column(NonZeroU64),
}
/// Deprecated. `LineNumberSequence` has been renamed to `LineSequence`.
#[deprecated(note = "LineNumberSequence has been renamed to LineSequence, use that instead.")]
pub type LineNumberSequence<R> = LineSequence<R>;
/// A sequence within a line number program. A sequence, as defined in section
/// 6.2.5 of the standard, is a linear subset of a line number program within
/// which addresses are monotonically increasing.
#[derive(Clone, Debug)]
pub struct LineSequence<R: Reader> {
/// The first address that is covered by this sequence within the line number
/// program.
pub start: u64,
/// The first address that is *not* covered by this sequence within the line
/// number program.
pub end: u64,
instructions: LineInstructions<R>,
}
/// Deprecated. `LineNumberProgramHeader` has been renamed to `LineProgramHeader`.
#[deprecated(
note = "LineNumberProgramHeader has been renamed to LineProgramHeader, use that instead."
)]
pub type LineNumberProgramHeader<R, Offset> = LineProgramHeader<R, Offset>;
/// A header for a line number program in the `.debug_line` section, as defined
/// in section 6.2.4 of the standard.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LineProgramHeader<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
encoding: Encoding,
offset: DebugLineOffset<Offset>,
unit_length: Offset,