Debian Codegraph @

third_party/rust/gimli/src/write/line.rs

raw
1 use alloc::vec::Vec;
2 use indexmap::{IndexMap, IndexSet};
3 use std::ops::{Deref, DerefMut};
4
5 use crate::common::{DebugLineOffset, Encoding, Format, LineEncoding, SectionId};
6 use crate::constants;
7 use crate::leb128;
8 use crate::write::{
9 Address, DebugLineStrOffsets, DebugStrOffsets, Error, LineStringId, LineStringTable, Result,
10 Section, StringId, Writer,
11 };
12
13 /// The number assigned to the first special opcode.
14 //
15 // We output all instructions for all DWARF versions, since readers
16 // should be able to ignore instructions they don't support.
17 const OPCODE_BASE: u8 = 13;
18
19 /// A line number program.
20 #[derive(Debug, Clone)]
21 pub struct LineProgram {
22 /// True if this line program was created with `LineProgram::none()`.
23 none: bool,
24 encoding: Encoding,
25 line_encoding: LineEncoding,
26
27 /// A list of source directory path names.
28 ///
29 /// If a path is relative, then the directory is located relative to the working
30 /// directory of the compilation unit.
31 ///
32 /// The first entry is for the working directory of the compilation unit.
33 directories: IndexSet<LineString>,
34
35 /// A list of source file entries.
36 ///
37 /// Each entry has a path name and a directory.
38 ///
39 /// If a path is a relative, then the file is located relative to the
40 /// directory. Otherwise the directory is meaningless.
41 ///
42 /// Does not include comp_file, even for version >= 5.
43 files: IndexMap<(LineString, DirectoryId), FileInfo>,
44
45 /// The primary source file of the compilation unit.
46 /// This is required for version >= 5, but we never reference it elsewhere
47 /// because DWARF defines DW_AT_decl_file=0 to mean not specified.
48 comp_file: (LineString, FileInfo),
49
50 /// True if the file entries may have valid timestamps.
51 ///
52 /// Entries may still have a timestamp of 0 even if this is set.
53 /// For version <= 4, this is ignored.
54 /// For version 5, this controls whether to emit `DW_LNCT_timestamp`.
55 pub file_has_timestamp: bool,
56
57 /// True if the file entries may have valid sizes.
58 ///
59 /// Entries may still have a size of 0 even if this is set.
60 /// For version <= 4, this is ignored.
61 /// For version 5, this controls whether to emit `DW_LNCT_size`.
62 pub file_has_size: bool,
63
64 /// True if the file entries have valid MD5 checksums.
65 ///
66 /// For version <= 4, this is ignored.
67 /// For version 5, this controls whether to emit `DW_LNCT_MD5`.
68 pub file_has_md5: bool,
69
70 /// True if the file entries have embedded source code.
71 ///
72 /// For version <= 4, this is ignored.
73 /// For version 5, this controls whether to emit `DW_LNCT_LLVM_source`.
74 pub file_has_source: bool,
75
76 prev_row: LineRow,
77 row: LineRow,
78 // TODO: this probably should be either rows or sequences instead
79 instructions: Vec<LineInstruction>,
80 in_sequence: bool,
81 }
82
83 impl LineProgram {
84 /// Create a new `LineProgram`.
85 ///
86 /// `comp_dir` defines the working directory of the compilation unit,
87 /// and must be the same as the `DW_AT_comp_dir` attribute
88 /// of the compilation unit DIE.
89 ///
90 /// `comp_file` and `comp_file_info` define the primary source file
91 /// of the compilation unit and must be the same as the `DW_AT_name`
92 /// attribute of the compilation unit DIE.
93 ///
94 /// # Panics
95 ///
96 /// Panics if `line_encoding.line_base` > 0.
97 ///
98 /// Panics if `line_encoding.line_base` + `line_encoding.line_range` <= 0.
99 ///
100 /// Panics if `comp_dir` is empty or contains a null byte.
101 ///
102 /// Panics if `comp_file` is empty or contains a null byte.
103 pub fn new(
104 encoding: Encoding,
105 line_encoding: LineEncoding,
106 comp_dir: LineString,
107 comp_file: LineString,
108 comp_file_info: Option<FileInfo>,
109 ) -> LineProgram {
110 // We require a special opcode for a line advance of 0.
111 // See the debug_asserts in generate_row().
112 assert!(line_encoding.line_base <= 0);
113 assert!(line_encoding.line_base + line_encoding.line_range as i8 > 0);
114 let mut program = LineProgram {
115 none: false,
116 encoding,
117 line_encoding,
118 directories: IndexSet::new(),
119 files: IndexMap::new(),
120 comp_file: (comp_file, comp_file_info.unwrap_or_default()),
121 prev_row: LineRow::initial_state(line_encoding),
122 row: LineRow::initial_state(line_encoding),
123 instructions: Vec::new(),
124 in_sequence: false,
125 file_has_timestamp: false,
126 file_has_size: false,
127 file_has_md5: false,
128 file_has_source: false,
129 };
130 // For all DWARF versions, directory index 0 is comp_dir.
131 // For version <= 4, the entry is implicit. We still add
132 // it here so that we use it, but we don't emit it.
133 program.add_directory(comp_dir);
134 program
135 }
136
137 /// Create a new `LineProgram` with no fields set.
138 ///
139 /// This can be used when the `LineProgram` will not be used.
140 ///
141 /// You should not attempt to add files or line instructions to
142 /// this line program, or write it to the `.debug_line` section.
143 pub fn none() -> Self {
144 let line_encoding = LineEncoding::default();
145 LineProgram {
146 none: true,
147 encoding: Encoding {
148 format: Format::Dwarf32,
149 version: 2,
150 address_size: 0,
151 },
152 line_encoding,
153 directories: IndexSet::new(),
154 files: IndexMap::new(),
155 comp_file: (LineString::String(Vec::new()), FileInfo::default()),
156 prev_row: LineRow::initial_state(line_encoding),
157 row: LineRow::initial_state(line_encoding),
158 instructions: Vec::new(),
159 in_sequence: false,
160 file_has_timestamp: false,
161 file_has_size: false,
162 file_has_md5: false,
163 file_has_source: false,
164 }
165 }
166
167 /// Return true if this line program was created with `LineProgram::none()`.
168 #[inline]
169 pub fn is_none(&self) -> bool {
170 self.none
171 }
172
173 /// Return the encoding parameters for this line program.
174 #[inline]
175 pub fn encoding(&self) -> Encoding {
176 self.encoding
177 }
178
179 /// Return the DWARF version for this line program.
180 #[inline]
181 pub fn version(&self) -> u16 {
182 self.encoding.version
183 }
184
185 /// Return the address size in bytes for this line program.
186 #[inline]
187 pub fn address_size(&self) -> u8 {
188 self.encoding.address_size
189 }
190
191 /// Return the DWARF format for this line program.
192 #[inline]
193 pub fn format(&self) -> Format {
194 self.encoding.format
195 }
196
197 /// Return the id for the working directory of the compilation unit.
198 #[inline]
199 pub fn default_directory(&self) -> DirectoryId {
200 DirectoryId(0)
201 }
202
203 /// Add a directory entry and return its id.
204 ///
205 /// If the directory already exists, then return the id of the existing entry.
206 ///
207 /// If the path is relative, then the directory is located relative to the working
208 /// directory of the compilation unit.
209 ///
210 /// # Panics
211 ///
212 /// Panics if `directory` is empty or contains a null byte.
213 pub fn add_directory(&mut self, directory: LineString) -> DirectoryId {
214 if let LineString::String(ref val) = directory {
215 // For DWARF version <= 4, directories must not be empty.
216 // The first directory isn't emitted so skip the check for it.
217 if self.encoding.version <= 4 && !self.directories.is_empty() {
218 assert!(!val.is_empty());
219 }
220 assert!(!val.contains(&0));
221 }
222 let (index, _) = self.directories.insert_full(directory);
223 DirectoryId(index)
224 }
225
226 /// Get a reference to a directory entry.
227 ///
228 /// # Panics
229 ///
230 /// Panics if `id` is invalid.
231 pub fn get_directory(&self, id: DirectoryId) -> &LineString {
232 self.directories.get_index(id.0).unwrap()
233 }
234
235 /// Add a file entry and return its id.
236 ///
237 /// If the file already exists, then return the id of the existing entry.
238 ///
239 /// If the file path is relative, then the file is located relative
240 /// to the directory. Otherwise the directory is meaningless, but it
241 /// is still used as a key for file entries.
242 ///
243 /// If `info` is `None`, then new entries are assigned
244 /// default information, and existing entries are unmodified.
245 ///
246 /// If `info` is not `None`, then it is always assigned to the
247 /// entry, even if the entry already exists.
248 ///
249 /// # Panics
250 ///
251 /// Panics if 'file' is empty or contains a null byte.
252 pub fn add_file(
253 &mut self,
254 file: LineString,
255 directory: DirectoryId,
256 info: Option<FileInfo>,
257 ) -> FileId {
258 if let LineString::String(ref val) = file {
259 assert!(!val.is_empty());
260 assert!(!val.contains(&0));
261 }
262
263 let key = (file, directory);
264 let index = if let Some(info) = info {
265 let (index, _) = self.files.insert_full(key, info);
266 index
267 } else {
268 let entry = self.files.entry(key);
269 let index = entry.index();
270 entry.or_default();
271 index
272 };
273 FileId::new(index)
274 }
275
276 /// Get a reference to a file entry.
277 ///
278 /// # Panics
279 ///
280 /// Panics if `id` is invalid.
281 pub fn get_file(&self, id: FileId) -> (&LineString, DirectoryId) {
282 match id.index() {
283 None => (&self.comp_file.0, DirectoryId(0)),
284 Some(index) => self
285 .files
286 .get_index(index)
287 .map(|entry| (&(entry.0).0, (entry.0).1))
288 .unwrap(),
289 }
290 }
291
292 /// Get a reference to the info for a file entry.
293 ///
294 /// # Panics
295 ///
296 /// Panics if `id` is invalid.
297 pub fn get_file_info(&self, id: FileId) -> &FileInfo {
298 match id.index() {
299 None => &self.comp_file.1,
300 Some(index) => self.files.get_index(index).map(|entry| entry.1).unwrap(),
301 }
302 }
303
304 /// Get a mutable reference to the info for a file entry.
305 ///
306 /// # Panics
307 ///
308 /// Panics if `id` is invalid.
309 pub fn get_file_info_mut(&mut self, id: FileId) -> &mut FileInfo {
310 match id.index() {
311 None => &mut self.comp_file.1,
312 Some(index) => self
313 .files
314 .get_index_mut(index)
315 .map(|entry| entry.1)
316 .unwrap(),
317 }
318 }
319
320 /// Begin a new sequence and set its base address.
321 ///
322 /// # Panics
323 ///
324 /// Panics if a sequence has already begun.
325 pub fn begin_sequence(&mut self, address: Option<Address>) {
326 assert!(!self.in_sequence);
327 self.in_sequence = true;
328 if let Some(address) = address {
329 self.instructions.push(LineInstruction::SetAddress(address));
330 }
331 }
332
333 /// End the sequence, and reset the row to its default values.
334 ///
335 /// Only the `address_offset` and op_index` fields of the current row are used.
336 ///
337 /// # Panics
338 ///
339 /// Panics if a sequence has not begun.
340 pub fn end_sequence(&mut self, address_offset: u64) {
341 assert!(self.in_sequence);
342 self.in_sequence = false;
343 self.row.address_offset = address_offset;
344 let op_advance = self.op_advance();
345 if op_advance != 0 {
346 self.instructions
347 .push(LineInstruction::AdvancePc(op_advance));
348 }
349 self.instructions.push(LineInstruction::EndSequence);
350 self.prev_row = LineRow::initial_state(self.line_encoding);
351 self.row = LineRow::initial_state(self.line_encoding);
352 }
353
354 /// Return true if a sequence has begun.
355 #[inline]
356 pub fn in_sequence(&self) -> bool {
357 self.in_sequence
358 }
359
360 /// Returns a reference to the data for the current row.
361 #[inline]
362 pub fn row(&mut self) -> &mut LineRow {
363 &mut self.row
364 }
365
366 /// Generates the line number information instructions for the current row.
367 ///
368 /// After the instructions are generated, it sets `discriminator` to 0, and sets
369 /// `basic_block`, `prologue_end`, and `epilogue_begin` to false.
370 ///
371 /// # Panics
372 ///
373 /// Panics if a sequence has not begun.
374 /// Panics if the address_offset decreases.
375 pub fn generate_row(&mut self) {
376 assert!(self.in_sequence);
377
378 // Output fields that are reset on every row.
379 if self.row.discriminator != 0 {
380 self.instructions
381 .push(LineInstruction::SetDiscriminator(self.row.discriminator));
382 self.row.discriminator = 0;
383 }
384 if self.row.basic_block {
385 self.instructions.push(LineInstruction::SetBasicBlock);
386 self.row.basic_block = false;
387 }
388 if self.row.prologue_end {
389 self.instructions.push(LineInstruction::SetPrologueEnd);
390 self.row.prologue_end = false;
391 }
392 if self.row.epilogue_begin {
393 self.instructions.push(LineInstruction::SetEpilogueBegin);
394 self.row.epilogue_begin = false;
395 }
396
397 // Output fields that are not reset on every row.
398 if self.row.is_statement != self.prev_row.is_statement {
399 self.instructions.push(LineInstruction::NegateStatement);
400 }
401 if self.row.file != self.prev_row.file {
402 self.instructions
403 .push(LineInstruction::SetFile(self.row.file));
404 }
405 if self.row.column != self.prev_row.column {
406 self.instructions
407 .push(LineInstruction::SetColumn(self.row.column));
408 }
409 if self.row.isa != self.prev_row.isa {
410 self.instructions
411 .push(LineInstruction::SetIsa(self.row.isa));
412 }
413
414 // Advance the line, address, and operation index.
415 let line_base = i64::from(self.line_encoding.line_base) as u64;
416 let line_range = u64::from(self.line_encoding.line_range);
417 let line_advance = self.row.line as i64 - self.prev_row.line as i64;
418 let op_advance = self.op_advance();
419
420 // Default to special advances of 0.
421 let special_base = u64::from(OPCODE_BASE);
422 // TODO: handle lack of special opcodes for 0 line advance
423 debug_assert!(self.line_encoding.line_base <= 0);
424 debug_assert!(self.line_encoding.line_base + self.line_encoding.line_range as i8 >= 0);
425 let special_default = special_base.wrapping_sub(line_base);
426 let mut special = special_default;
427 let mut use_special = false;
428
429 if line_advance != 0 {
430 let special_line = (line_advance as u64).wrapping_sub(line_base);
431 if special_line < line_range {
432 special = special_base + special_line;
433 use_special = true;
434 } else {
435 self.instructions
436 .push(LineInstruction::AdvanceLine(line_advance));
437 }
438 }
439
440 if op_advance != 0 {
441 // Using ConstAddPc can save a byte.
442 let (special_op_advance, const_add_pc) = if special + op_advance * line_range <= 255 {
443 (op_advance, false)
444 } else {
445 let op_range = (255 - special_base) / line_range;
446 (op_advance - op_range, true)
447 };
448
449 let special_op = special_op_advance * line_range;
450 if special + special_op <= 255 {
451 special += special_op;
452 use_special = true;
453 if const_add_pc {
454 self.instructions.push(LineInstruction::ConstAddPc);
455 }
456 } else {
457 self.instructions
458 .push(LineInstruction::AdvancePc(op_advance));
459 }
460 }
461
462 if use_special && special != special_default {
463 debug_assert!(special >= special_base);
464 debug_assert!(special <= 255);
465 self.instructions
466 .push(LineInstruction::Special(special as u8));
467 } else {
468 self.instructions.push(LineInstruction::Copy);
469 }
470
471 self.prev_row = self.row;
472 }
473
474 fn op_advance(&self) -> u64 {
475 debug_assert!(self.row.address_offset >= self.prev_row.address_offset);
476 let mut address_advance = self.row.address_offset - self.prev_row.address_offset;
477 if self.line_encoding.minimum_instruction_length != 1 {
478 debug_assert_eq!(
479 self.row.address_offset % u64::from(self.line_encoding.minimum_instruction_length),
480 0
481 );
482 address_advance /= u64::from(self.line_encoding.minimum_instruction_length);
483 }
484 address_advance * u64::from(self.line_encoding.maximum_operations_per_instruction)
485 + self.row.op_index
486 - self.prev_row.op_index
487 }
488
489 /// Returns true if the line number program has no instructions.
490 ///
491 /// Does not check the file or directory entries.
492 #[inline]
493 pub fn is_empty(&self) -> bool {
494 self.instructions.is_empty()
495 }
496
497 /// Write the line number program to the given section.
498 ///
499 /// # Panics
500 ///
501 /// Panics if `self.is_none()`.
502 pub fn write<W: Writer>(
503 &self,
504 w: &mut DebugLine<W>,
505 encoding: Encoding,
506 debug_line_str_offsets: &DebugLineStrOffsets,
507 debug_str_offsets: &DebugStrOffsets,
508 ) -> Result<DebugLineOffset> {
509 assert!(!self.is_none());
510
511 if encoding.version < self.version()
512 || encoding.format != self.format()
513 || encoding.address_size != self.address_size()
514 {
515 return Err(Error::IncompatibleLineProgramEncoding);
516 }
517
518 let offset = w.offset();
519
520 let length_offset = w.write_initial_length(self.format())?;
521 let length_base = w.len();
522
523 if self.version() < 2 || self.version() > 5 {
524 return Err(Error::UnsupportedVersion(self.version()));
525 }
526 w.write_u16(self.version())?;
527
528 if self.version() >= 5 {
529 w.write_u8(self.address_size())?;
530 // Segment selector size.
531 w.write_u8(0)?;
532 }
533
534 let header_length_offset = w.len();
535 w.write_udata(0, self.format().word_size())?;
536 let header_length_base = w.len();
537
538 w.write_u8(self.line_encoding.minimum_instruction_length)?;
539 if self.version() >= 4 {
540 w.write_u8(self.line_encoding.maximum_operations_per_instruction)?;
541 } else if self.line_encoding.maximum_operations_per_instruction != 1 {
542 return Err(Error::NeedVersion(4));
543 };
544 w.write_u8(if self.line_encoding.default_is_stmt {
545 1
546 } else {
547 0
548 })?;
549 w.write_u8(self.line_encoding.line_base as u8)?;
550 w.write_u8(self.line_encoding.line_range)?;
551 w.write_u8(OPCODE_BASE)?;
552 w.write(&[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1])?;
553
554 if self.version() <= 4 {
555 // The first directory is stored as DW_AT_comp_dir.
556 for dir in self.directories.iter().skip(1) {
557 dir.write(
558 w,
559 constants::DW_FORM_string,
560 self.encoding,
561 debug_line_str_offsets,
562 debug_str_offsets,
563 )?;
564 }
565 w.write_u8(0)?;
566
567 for ((file, dir), info) in self.files.iter() {
568 file.write(
569 w,
570 constants::DW_FORM_string,
571 self.encoding,
572 debug_line_str_offsets,
573 debug_str_offsets,
574 )?;
575 w.write_uleb128(dir.0 as u64)?;
576 w.write_uleb128(info.timestamp)?;
577 w.write_uleb128(info.size)?;
578 }
579 w.write_u8(0)?;
580 } else {
581 // Directory entry formats (only ever 1).
582 w.write_u8(1)?;
583 w.write_uleb128(u64::from(constants::DW_LNCT_path.0))?;
584 let dir_form = self.directories.get_index(0).unwrap().form();
585 w.write_uleb128(dir_form.0.into())?;
586
587 // Directory entries.
588 w.write_uleb128(self.directories.len() as u64)?;
589 for dir in self.directories.iter() {
590 dir.write(
591 w,
592 dir_form,
593 self.encoding,
594 debug_line_str_offsets,
595 debug_str_offsets,
596 )?;
597 }
598
599 // File name entry formats.
600 let count = 2
601 + if self.file_has_timestamp { 1 } else { 0 }
602 + if self.file_has_size { 1 } else { 0 }
603 + if self.file_has_md5 { 1 } else { 0 }
604 + if self.file_has_source { 1 } else { 0 };
605 w.write_u8(count)?;
606 w.write_uleb128(u64::from(constants::DW_LNCT_path.0))?;
607 let file_form = self.comp_file.0.form();
608 w.write_uleb128(file_form.0.into())?;
609 w.write_uleb128(u64::from(constants::DW_LNCT_directory_index.0))?;
610 w.write_uleb128(constants::DW_FORM_udata.0.into())?;
611 if self.file_has_timestamp {
612 w.write_uleb128(u64::from(constants::DW_LNCT_timestamp.0))?;
613 w.write_uleb128(constants::DW_FORM_udata.0.into())?;
614 }
615 if self.file_has_size {
616 w.write_uleb128(u64::from(constants::DW_LNCT_size.0))?;
617 w.write_uleb128(constants::DW_FORM_udata.0.into())?;
618 }
619 if self.file_has_md5 {
620 w.write_uleb128(u64::from(constants::DW_LNCT_MD5.0))?;
621 w.write_uleb128(constants::DW_FORM_data16.0.into())?;
622 }
623 if self.file_has_source {
624 w.write_uleb128(u64::from(constants::DW_LNCT_LLVM_source.0))?;
625 w.write_uleb128(constants::DW_FORM_string.0.into())?;
626 }
627
628 // File name entries.
629 w.write_uleb128(self.files.len() as u64 + 1)?;
630 let mut write_file = |file: &LineString, dir: DirectoryId, info: &FileInfo| {
631 file.write(
632 w,
633 file_form,
634 self.encoding,
635 debug_line_str_offsets,
636 debug_str_offsets,
637 )?;
638 w.write_uleb128(dir.0 as u64)?;
639 if self.file_has_timestamp {
640 w.write_uleb128(info.timestamp)?;
641 }
642 if self.file_has_size {
643 w.write_uleb128(info.size)?;
644 }
645 if self.file_has_md5 {
646 w.write(&info.md5)?;
647 }
648 if self.file_has_source {
649 // Note: An empty DW_LNCT_LLVM_source is interpreted as missing
650 // source code. Included source code should always be
651 // terminated by a "\n" line ending.
652 let empty_str = LineString::String(Vec::new());
653 let source = info.source.as_ref().unwrap_or(&empty_str);
654 source.write(
655 w,
656 constants::DW_FORM_string,
657 self.encoding,
658 debug_line_str_offsets,
659 debug_str_offsets,
660 )?;
661 }
662 Ok(())
663 };
664 write_file(&self.comp_file.0, DirectoryId(0), &self.comp_file.1)?;
665 for ((file, dir), info) in self.files.iter() {
666 write_file(file, *dir, info)?;
667 }
668 }
669
670 let header_length = (w.len() - header_length_base) as u64;
671 w.write_udata_at(
672 header_length_offset,
673 header_length,
674 self.format().word_size(),
675 )?;
676
677 for instruction in &self.instructions {
678 instruction.write(w, self.address_size())?;
679 }
680
681 let length = (w.len() - length_base) as u64;
682 w.write_initial_length_at(length_offset, length, self.format())?;
683
684 Ok(offset)
685 }
686 }
687
688 /// A row in the line number table that corresponds to a machine instruction.
689 #[derive(Debug, Clone, Copy)]
690 pub struct LineRow {
691 /// The offset of the instruction from the start address of the sequence.
692 pub address_offset: u64,
693 /// The index of an operation within a VLIW instruction.
694 ///
695 /// The index of the first operation is 0.
696 /// Set to 0 for non-VLIW instructions.
697 pub op_index: u64,
698
699 /// The source file corresponding to the instruction.
700 pub file: FileId,
701 /// The line number within the source file.
702 ///
703 /// Lines are numbered beginning at 1. Set to 0 if there is no source line.
704 pub line: u64,
705 /// The column number within the source line.
706 ///
707 /// Columns are numbered beginning at 1. Set to 0 for the "left edge" of the line.
708 pub column: u64,
709 /// An additional discriminator used to distinguish between source locations.
710 /// This value is assigned arbitrarily by the DWARF producer.
711 pub discriminator: u64,
712
713 /// Set to true if the instruction is a recommended breakpoint for a statement.
714 pub is_statement: bool,
715 /// Set to true if the instruction is the beginning of a basic block.
716 pub basic_block: bool,
717 /// Set to true if the instruction is a recommended breakpoint at the entry of a
718 /// function.
719 pub prologue_end: bool,
720 /// Set to true if the instruction is a recommended breakpoint prior to the exit of
721 /// a function.
722 pub epilogue_begin: bool,
723
724 /// The instruction set architecture of the instruction.
725 ///
726 /// Set to 0 for the default ISA. Other values are defined by the architecture ABI.
727 pub isa: u64,
728 }
729
730 impl LineRow {
731 /// Return the initial state as specified in the DWARF standard.
732 fn initial_state(line_encoding: LineEncoding) -> Self {
733 LineRow {
734 address_offset: 0,
735 op_index: 0,
736
737 file: FileId::initial_state(),
738 line: 1,
739 column: 0,
740 discriminator: 0,
741
742 is_statement: line_encoding.default_is_stmt,
743 basic_block: false,
744 prologue_end: false,
745 epilogue_begin: false,
746
747 isa: 0,
748 }
749 }
750 }
751
752 /// An instruction in a line number program.
753 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
754 enum LineInstruction {
755 // Special opcodes
756 Special(u8),
757
758 // Standard opcodes
759 Copy,
760 AdvancePc(u64),
761 AdvanceLine(i64),
762 SetFile(FileId),
763 SetColumn(u64),
764 NegateStatement,
765 SetBasicBlock,
766 ConstAddPc,
767 // DW_LNS_fixed_advance_pc is not supported.
768 SetPrologueEnd,
769 SetEpilogueBegin,
770 SetIsa(u64),
771
772 // Extended opcodes
773 EndSequence,
774 // TODO: this doubles the size of this enum.
775 SetAddress(Address),
776 // DW_LNE_define_file is not supported.
777 SetDiscriminator(u64),
778 }
779
780 impl LineInstruction {
781 /// Write the line number instruction to the given section.
782 fn write<W: Writer>(self, w: &mut DebugLine<W>, address_size: u8) -> Result<()> {
783 use self::LineInstruction::*;
784 match self {
785 Special(val) => w.write_u8(val)?,
786 Copy => w.write_u8(constants::DW_LNS_copy.0)?,
787 AdvancePc(val) => {
788 w.write_u8(constants::DW_LNS_advance_pc.0)?;
789 w.write_uleb128(val)?;
790 }
791 AdvanceLine(val) => {
792 w.write_u8(constants::DW_LNS_advance_line.0)?;
793 w.write_sleb128(val)?;
794 }
795 SetFile(val) => {
796 w.write_u8(constants::DW_LNS_set_file.0)?;
797 w.write_uleb128(val.raw())?;
798 }
799 SetColumn(val) => {
800 w.write_u8(constants::DW_LNS_set_column.0)?;
801 w.write_uleb128(val)?;
802 }
803 NegateStatement => w.write_u8(constants::DW_LNS_negate_stmt.0)?,
804 SetBasicBlock => w.write_u8(constants::DW_LNS_set_basic_block.0)?,
805 ConstAddPc => w.write_u8(constants::DW_LNS_const_add_pc.0)?,
806 SetPrologueEnd => w.write_u8(constants::DW_LNS_set_prologue_end.0)?,
807 SetEpilogueBegin => w.write_u8(constants::DW_LNS_set_epilogue_begin.0)?,
808 SetIsa(val) => {
809 w.write_u8(constants::DW_LNS_set_isa.0)?;
810 w.write_uleb128(val)?;
811 }
812 EndSequence => {
813 w.write_u8(0)?;
814 w.write_uleb128(1)?;
815 w.write_u8(constants::DW_LNE_end_sequence.0)?;
816 }
817 SetAddress(address) => {
818 w.write_u8(0)?;
819 w.write_uleb128(1 + u64::from(address_size))?;
820 w.write_u8(constants::DW_LNE_set_address.0)?;
821 w.write_address(address, address_size)?;
822 }
823 SetDiscriminator(val) => {
824 let mut bytes = [0u8; 10];
825 // bytes is long enough so this will never fail.
826 let len = leb128::write::unsigned(&mut { &mut bytes[..] }, val).unwrap();
827 w.write_u8(0)?;
828 w.write_uleb128(1 + len as u64)?;
829 w.write_u8(constants::DW_LNE_set_discriminator.0)?;
830 w.write(&bytes[..len])?;
831 }
832 }
833 Ok(())
834 }
835 }
836
837 /// A string value for use in defining paths in line number programs.
838 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
839 pub enum LineString {
840 /// A slice of bytes representing a string. Must not include null bytes.
841 /// Not guaranteed to be UTF-8 or anything like that.
842 String(Vec<u8>),
843
844 /// A reference to a string in the `.debug_str` section.
845 StringRef(StringId),
846
847 /// A reference to a string in the `.debug_line_str` section.
848 LineStringRef(LineStringId),
849 }
850
851 impl LineString {
852 /// Create a `LineString` using the normal form for the given encoding.
853 pub fn new<T>(val: T, encoding: Encoding, line_strings: &mut LineStringTable) -> Self
854 where
855 T: Into<Vec<u8>>,
856 {
857 let val = val.into();
858 if encoding.version <= 4 {
859 LineString::String(val)
860 } else {
861 LineString::LineStringRef(line_strings.add(val))
862 }
863 }
864
865 fn form(&self) -> constants::DwForm {
866 match *self {
867 LineString::String(..) => constants::DW_FORM_string,
868 LineString::StringRef(..) => constants::DW_FORM_strp,
869 LineString::LineStringRef(..) => constants::DW_FORM_line_strp,
870 }
871 }
872
873 fn write<W: Writer>(
874 &self,
875 w: &mut DebugLine<W>,
876 form: constants::DwForm,
877 encoding: Encoding,
878 debug_line_str_offsets: &DebugLineStrOffsets,
879 debug_str_offsets: &DebugStrOffsets,
880 ) -> Result<()> {
881 if form != self.form() {
882 return Err(Error::LineStringFormMismatch);
883 }
884
885 match *self {
886 LineString::String(ref val) => {
887 if encoding.version <= 4 {
888 debug_assert!(!val.is_empty());
889 }
890 w.write(val)?;
891 w.write_u8(0)?;
892 }
893 LineString::StringRef(val) => {
894 if encoding.version < 5 {
895 return Err(Error::NeedVersion(5));
896 }
897 w.write_offset(
898 debug_str_offsets.get(val).0,
899 SectionId::DebugStr,
900 encoding.format.word_size(),
901 )?;
902 }
903 LineString::LineStringRef(val) => {
904 if encoding.version < 5 {
905 return Err(Error::NeedVersion(5));
906 }
907 w.write_offset(
908 debug_line_str_offsets.get(val).0,
909 SectionId::DebugLineStr,
910 encoding.format.word_size(),
911 )?;
912 }
913 }
914 Ok(())
915 }
916 }
917
918 /// An identifier for a directory in a `LineProgram`.
919 ///
920 /// Defaults to the working directory of the compilation unit.
921 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
922 pub struct DirectoryId(usize);
923
924 // Force FileId access via the methods.
925 mod id {
926 /// An identifier for a file in a `LineProgram`.
927 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
928 pub struct FileId(usize);
929
930 impl FileId {
931 /// Create a FileId given an index into `LineProgram::files`.
932 pub(crate) fn new(index: usize) -> Self {
933 FileId(index + 1)
934 }
935
936 /// The index of the file in `LineProgram::files`.
937 pub(super) fn index(self) -> Option<usize> {
938 if self.0 == 0 {
939 None
940 } else {
941 Some(self.0 - 1)
942 }
943 }
944
945 /// The initial state of the file register.
946 pub(super) fn initial_state() -> Self {
947 FileId(1)
948 }
949
950 /// The raw value used when writing.
951 pub(crate) fn raw(self) -> u64 {
952 self.0 as u64
953 }
954
955 /// The id for file index 0 in DWARF version 5.
956 /// Only used when converting.
957 // Used for tests only.
958 #[allow(unused)]
959 pub(super) fn zero() -> Self {
960 FileId(0)
961 }
962 }
963 }
964 pub use self::id::*;
965
966 /// Extra information for file in a `LineProgram`.
967 #[derive(Debug, Default, Clone, PartialEq, Eq)]
968 pub struct FileInfo {
969 /// The implementation defined timestamp of the last modification of the file,
970 /// or 0 if not available.
971 pub timestamp: u64,
972
973 /// The size of the file in bytes, or 0 if not available.
974 pub size: u64,
975
976 /// A 16-byte MD5 digest of the file contents.
977 ///
978 /// Only used if version >= 5 and `LineProgram::file_has_md5` is `true`.
979 pub md5: [u8; 16],
980
981 /// Optionally some embedded sourcecode.
982 ///
983 /// Only used if version >= 5 and `LineProgram::file_has_source` is `true`.
984 ///
985 /// NOTE: This currently only supports the `LineString::String` variant,
986 /// since we're encoding the string with `DW_FORM_string`.
987 /// Other variants will result in an `LineStringFormMismatch` error.
988 pub source: Option<LineString>,
989 }
990
991 define_section!(
992 DebugLine,
993 DebugLineOffset,
994 "A writable `.debug_line` section."
995 );
996
997 #[cfg(feature = "read")]
998 mod convert {
999 use super::*;
1000 use crate::read::{self, Reader};
1001 use crate::write::{self, ConvertError, ConvertResult};
1002
1003 impl LineProgram {
1004 /// Create a line number program by reading the data from the given program.
1005 ///
1006 /// Return the program and a mapping from file index to `FileId`.
1007 pub fn from<R: Reader<Offset = usize>>(
1008 mut from_program: read::IncompleteLineProgram<R>,
1009 dwarf: &read::Dwarf<R>,
1010 line_strings: &mut write::LineStringTable,
1011 strings: &mut write::StringTable,
1012 convert_address: &dyn Fn(u64) -> Option<Address>,
1013 ) -> ConvertResult<(LineProgram, Vec<FileId>)> {
1014 // Create mappings in case the source has duplicate files or directories.
1015 let mut dirs = Vec::new();
1016 let mut files = Vec::new();
1017
1018 let mut program = {
1019 let from_header = from_program.header();
1020 let encoding = from_header.encoding();
1021
1022 let comp_dir = match from_header.directory(0) {
1023 Some(comp_dir) => LineString::from(comp_dir, dwarf, line_strings, strings)?,
1024 None => LineString::new(&[][..], encoding, line_strings),
1025 };
1026
1027 let (comp_name, comp_file_info) = match from_header.file(0) {
1028 Some(comp_file) => {
1029 if comp_file.directory_index() != 0 {
1030 return Err(ConvertError::InvalidDirectoryIndex);
1031 }
1032 (
1033 LineString::from(comp_file.path_name(), dwarf, line_strings, strings)?,
1034 Some(FileInfo {
1035 timestamp: comp_file.timestamp(),
1036 size: comp_file.size(),
1037 md5: *comp_file.md5(),
1038 source: match comp_file.source() {
1039 Some(source) => Some(LineString::from(
1040 source,
1041 dwarf,
1042 line_strings,
1043 strings,
1044 )?),
1045 None => None,
1046 },
1047 }),
1048 )
1049 }
1050 None => (LineString::new(&[][..], encoding, line_strings), None),
1051 };
1052
1053 if from_header.line_base() > 0 {
1054 return Err(ConvertError::InvalidLineBase);
1055 }
1056 let mut program = LineProgram::new(
1057 encoding,
1058 from_header.line_encoding(),
1059 comp_dir,
1060 comp_name,
1061 comp_file_info,
1062 );
1063
1064 let file_skip;
1065 if from_header.version() <= 4 {
1066 // The first directory is implicit.
1067 dirs.push(DirectoryId(0));
1068 // A file index of 0 is invalid for version <= 4, but putting
1069 // something there makes the indexing easier.
1070 file_skip = 0;
1071 files.push(FileId::zero());
1072 } else {
1073 // We don't add the first file to `files`, but still allow
1074 // it to be referenced from converted instructions.
1075 file_skip = 1;
1076 files.push(FileId::zero());
1077 }
1078
1079 for from_dir in from_header.include_directories() {
1080 let from_dir =
1081 LineString::from(from_dir.clone(), dwarf, line_strings, strings)?;
1082 dirs.push(program.add_directory(from_dir));
1083 }
1084
1085 program.file_has_timestamp = from_header.file_has_timestamp();
1086 program.file_has_size = from_header.file_has_size();
1087 program.file_has_md5 = from_header.file_has_md5();
1088 program.file_has_source = from_header.file_has_source();
1089 for from_file in from_header.file_names().iter().skip(file_skip) {
1090 let from_name =
1091 LineString::from(from_file.path_name(), dwarf, line_strings, strings)?;
1092 let from_dir = from_file.directory_index();
1093 if from_dir >= dirs.len() as u64 {
1094 return Err(ConvertError::InvalidDirectoryIndex);
1095 }
1096 let from_dir = dirs[from_dir as usize];
1097 let from_info = Some(FileInfo {
1098 timestamp: from_file.timestamp(),
1099 size: from_file.size(),
1100 md5: *from_file.md5(),
1101 source: match from_file.source() {
1102 Some(source) => {
1103 Some(LineString::from(source, dwarf, line_strings, strings)?)
1104 }
1105 None => None,
1106 },
1107 });
1108 files.push(program.add_file(from_name, from_dir, from_info));
1109 }
1110
1111 program
1112 };
1113
1114 // We can't use the `from_program.rows()` because that wouldn't let
1115 // us preserve address relocations.
1116 let mut from_row = read::LineRow::new(from_program.header());
1117 let mut instructions = from_program.header().instructions();
1118 let mut address = None;
1119 while let Some(instruction) = instructions.next_instruction(from_program.header())? {
1120 match instruction {
1121 read::LineInstruction::SetAddress(val) => {
1122 if program.in_sequence() {
1123 return Err(ConvertError::UnsupportedLineInstruction);
1124 }
1125 match convert_address(val) {
1126 Some(val) => address = Some(val),
1127 None => return Err(ConvertError::InvalidAddress),
1128 }
1129 from_row
1130 .execute(read::LineInstruction::SetAddress(0), &mut from_program)?;
1131 }
1132 read::LineInstruction::DefineFile(_) => {
1133 return Err(ConvertError::UnsupportedLineInstruction);
1134 }
1135 _ => {
1136 if from_row.execute(instruction, &mut from_program)? {
1137 if !program.in_sequence() {
1138 program.begin_sequence(address);
1139 address = None;
1140 }
1141 if from_row.end_sequence() {
1142 program.end_sequence(from_row.address());
1143 } else {
1144 program.row().address_offset = from_row.address();
1145 program.row().op_index = from_row.op_index();
1146 program.row().file = {
1147 let file = from_row.file_index();
1148 if file >= files.len() as u64 {
1149 return Err(ConvertError::InvalidFileIndex);
1150 }
1151 if file == 0 && program.version() <= 4 {
1152 return Err(ConvertError::InvalidFileIndex);
1153 }
1154 files[file as usize]
1155 };
1156 program.row().line = match from_row.line() {
1157 Some(line) => line.get(),
1158 None => 0,
1159 };
1160 program.row().column = match from_row.column() {
1161 read::ColumnType::LeftEdge => 0,
1162 read::ColumnType::Column(val) => val.get(),
1163 };
1164 program.row().discriminator = from_row.discriminator();
1165 program.row().is_statement = from_row.is_stmt();
1166 program.row().basic_block = from_row.basic_block();
1167 program.row().prologue_end = from_row.prologue_end();
1168 program.row().epilogue_begin = from_row.epilogue_begin();
1169 program.row().isa = from_row.isa();
1170 program.generate_row();
1171 }
1172 from_row.reset(from_program.header());
1173 }
1174 }
1175 };
1176 }
1177 Ok((program, files))
1178 }
1179 }
1180
1181 impl LineString {
1182 fn from<R: Reader<Offset = usize>>(
1183 from_attr: read::AttributeValue<R>,
1184 dwarf: &read::Dwarf<R>,
1185 line_strings: &mut write::LineStringTable,
1186 strings: &mut write::StringTable,
1187 ) -> ConvertResult<LineString> {
1188 Ok(match from_attr {
1189 read::AttributeValue::String(r) => LineString::String(r.to_slice()?.to_vec()),
1190 read::AttributeValue::DebugStrRef(offset) => {
1191 let r = dwarf.debug_str.get_str(offset)?;
1192 let id = strings.add(r.to_slice()?);
1193 LineString::StringRef(id)
1194 }
1195 read::AttributeValue::DebugLineStrRef(offset) => {
1196 let r = dwarf.debug_line_str.get_str(offset)?;
1197 let id = line_strings.add(r.to_slice()?);
1198 LineString::LineStringRef(id)
1199 }
1200 _ => return Err(ConvertError::UnsupportedLineStringForm),
1201 })
1202 }
1203 }
1204 }
1205
1206 #[cfg(test)]
1207 #[cfg(feature = "read")]
1208 mod tests {
1209 use super::*;
1210 use crate::read;
1211 use crate::write::{DebugLineStr, DebugStr, EndianVec, StringTable};
1212 use crate::LittleEndian;
1213
1214 #[test]
1215 fn test_line_program_table() {
1216 let dir1 = LineString::String(b"dir1".to_vec());
1217 let file1 = LineString::String(b"file1".to_vec());
1218 let dir2 = LineString::String(b"dir2".to_vec());
1219 let file2 = LineString::String(b"file2".to_vec());
1220
1221 let mut programs = Vec::new();
1222 for &version in &[2, 3, 4, 5] {
1223 for &address_size in &[4, 8] {
1224 for &format in &[Format::Dwarf32, Format::Dwarf64] {
1225 let encoding = Encoding {
1226 format,
1227 version,
1228 address_size,
1229 };
1230 let mut program = LineProgram::new(
1231 encoding,
1232 LineEncoding::default(),
1233 dir1.clone(),
1234 file1.clone(),
1235 None,
1236 );
1237
1238 {
1239 assert_eq!(&dir1, program.get_directory(program.default_directory()));
1240 program.file_has_timestamp = true;
1241 program.file_has_size = true;
1242 if encoding.version >= 5 {
1243 program.file_has_md5 = true;
1244 }
1245
1246 // Note: Embedded source code is an accepted extension
1247 // that will become part of DWARF v6. We're using the LLVM extension
1248 // here for v5.
1249 if encoding.version >= 5 {
1250 program.file_has_source = true;
1251 }
1252
1253 let dir_id = program.add_directory(dir2.clone());
1254 assert_eq!(&dir2, program.get_directory(dir_id));
1255 assert_eq!(dir_id, program.add_directory(dir2.clone()));
1256
1257 let file_info = FileInfo {
1258 timestamp: 1,
1259 size: 2,
1260 md5: if encoding.version >= 5 {
1261 [3; 16]
1262 } else {
1263 [0; 16]
1264 },
1265 source: (encoding.version >= 5)
1266 .then(|| LineString::String(b"the source code\n".to_vec())),
1267 };
1268 let file_id =
1269 program.add_file(file2.clone(), dir_id, Some(file_info.clone()));
1270 assert_eq!((&file2, dir_id), program.get_file(file_id));
1271 assert_eq!(file_info, *program.get_file_info(file_id));
1272
1273 program.get_file_info_mut(file_id).size = 3;
1274 assert_ne!(file_info, *program.get_file_info(file_id));
1275 assert_eq!(file_id, program.add_file(file2.clone(), dir_id, None));
1276 assert_ne!(file_info, *program.get_file_info(file_id));
1277 assert_eq!(
1278 file_id,
1279 program.add_file(file2.clone(), dir_id, Some(file_info.clone()))
1280 );
1281 assert_eq!(file_info, *program.get_file_info(file_id));
1282
1283 programs.push((program, file_id, encoding));
1284 }
1285 }
1286 }
1287 }
1288
1289 let debug_line_str_offsets = DebugLineStrOffsets::none();
1290 let debug_str_offsets = DebugStrOffsets::none();
1291 let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian));
1292 let mut debug_line_offsets = Vec::new();
1293 for (program, _, encoding) in &programs {
1294 debug_line_offsets.push(
1295 program
1296 .write(
1297 &mut debug_line,
1298 *encoding,
1299 &debug_line_str_offsets,
1300 &debug_str_offsets,
1301 )
1302 .unwrap(),
1303 );
1304 }
1305
1306 let read_debug_line = read::DebugLine::new(debug_line.slice(), LittleEndian);
1307
1308 let convert_address = &|address| Some(Address::Constant(address));
1309 for ((program, file_id, encoding), offset) in programs.iter().zip(debug_line_offsets.iter())
1310 {
1311 let read_program = read_debug_line
1312 .program(
1313 *offset,
1314 encoding.address_size,
1315 Some(read::EndianSlice::new(b"dir1", LittleEndian)),
1316 Some(read::EndianSlice::new(b"file1", LittleEndian)),
1317 )
1318 .unwrap();
1319
1320 let dwarf = read::Dwarf::default();
1321 let mut convert_line_strings = LineStringTable::default();
1322 let mut convert_strings = StringTable::default();
1323 let (convert_program, convert_files) = LineProgram::from(
1324 read_program,
1325 &dwarf,
1326 &mut convert_line_strings,
1327 &mut convert_strings,
1328 convert_address,
1329 )
1330 .unwrap();
1331 assert_eq!(convert_program.version(), program.version());
1332 assert_eq!(convert_program.address_size(), program.address_size());
1333 assert_eq!(convert_program.format(), program.format());
1334
1335 let convert_file_id = convert_files[file_id.raw() as usize];
1336 let (file, dir) = program.get_file(*file_id);
1337 let (convert_file, convert_dir) = convert_program.get_file(convert_file_id);
1338 assert_eq!(file, convert_file);
1339 assert_eq!(
1340 program.get_directory(dir),
1341 convert_program.get_directory(convert_dir)
1342 );
1343 assert_eq!(
1344 program.get_file_info(*file_id),
1345 convert_program.get_file_info(convert_file_id)
1346 );
1347 }
1348 }
1349
1350 #[test]
1351 fn test_line_row() {
1352 let dir1 = &b"dir1"[..];
1353 let file1 = &b"file1"[..];
1354 let file2 = &b"file2"[..];
1355 let convert_address = &|address| Some(Address::Constant(address));
1356
1357 let debug_line_str_offsets = DebugLineStrOffsets::none();
1358 let debug_str_offsets = DebugStrOffsets::none();
1359
1360 for &version in &[2, 3, 4, 5] {
1361 for &address_size in &[4, 8] {
1362 for &format in &[Format::Dwarf32, Format::Dwarf64] {
1363 let encoding = Encoding {
1364 format,
1365 version,
1366 address_size,
1367 };
1368 let line_base = -5;
1369 let line_range = 14;
1370 let neg_line_base = (-line_base) as u8;
1371 let mut program = LineProgram::new(
1372 encoding,
1373 LineEncoding {
1374 line_base,
1375 line_range,
1376 ..Default::default()
1377 },
1378 LineString::String(dir1.to_vec()),
1379 LineString::String(file1.to_vec()),
1380 None,
1381 );
1382 let dir_id = program.default_directory();
1383 program.add_file(LineString::String(file1.to_vec()), dir_id, None);
1384 let file_id =
1385 program.add_file(LineString::String(file2.to_vec()), dir_id, None);
1386
1387 // Test sequences.
1388 {
1389 let mut program = program.clone();
1390 let address = Address::Constant(0x12);
1391 program.begin_sequence(Some(address));
1392 assert_eq!(
1393 program.instructions,
1394 vec![LineInstruction::SetAddress(address)]
1395 );
1396 }
1397
1398 {
1399 let mut program = program.clone();
1400 program.begin_sequence(None);
1401 assert_eq!(program.instructions, Vec::new());
1402 }
1403
1404 {
1405 let mut program = program.clone();
1406 program.begin_sequence(None);
1407 program.end_sequence(0x1234);
1408 assert_eq!(
1409 program.instructions,
1410 vec![
1411 LineInstruction::AdvancePc(0x1234),
1412 LineInstruction::EndSequence
1413 ]
1414 );
1415 }
1416
1417 // Create a base program.
1418 program.begin_sequence(None);
1419 program.row.line = 0x1000;
1420 program.generate_row();
1421 let base_row = program.row;
1422 let base_instructions = program.instructions.clone();
1423
1424 // Create test cases.
1425 let mut tests = Vec::new();
1426
1427 let row = base_row;
1428 tests.push((row, vec![LineInstruction::Copy]));
1429
1430 let mut row = base_row;
1431 row.line -= u64::from(neg_line_base);
1432 tests.push((row, vec![LineInstruction::Special(OPCODE_BASE)]));
1433
1434 let mut row = base_row;
1435 row.line += u64::from(line_range) - 1;
1436 row.line -= u64::from(neg_line_base);
1437 tests.push((
1438 row,
1439 vec![LineInstruction::Special(OPCODE_BASE + line_range - 1)],
1440 ));
1441
1442 let mut row = base_row;
1443 row.line += u64::from(line_range);
1444 row.line -= u64::from(neg_line_base);
1445 tests.push((
1446 row,
1447 vec![
1448 LineInstruction::AdvanceLine(i64::from(line_range - neg_line_base)),
1449 LineInstruction::Copy,
1450 ],
1451 ));
1452
1453 let mut row = base_row;
1454 row.address_offset = 1;
1455 row.line -= u64::from(neg_line_base);
1456 tests.push((
1457 row,
1458 vec![LineInstruction::Special(OPCODE_BASE + line_range)],
1459 ));
1460
1461 let op_range = (255 - OPCODE_BASE) / line_range;
1462 let mut row = base_row;
1463 row.address_offset = u64::from(op_range);
1464 row.line -= u64::from(neg_line_base);
1465 tests.push((
1466 row,
1467 vec![LineInstruction::Special(
1468 OPCODE_BASE + op_range * line_range,
1469 )],
1470 ));
1471
1472 let mut row = base_row;
1473 row.address_offset = u64::from(op_range);
1474 row.line += u64::from(255 - OPCODE_BASE - op_range * line_range);
1475 row.line -= u64::from(neg_line_base);
1476 tests.push((row, vec![LineInstruction::Special(255)]));
1477
1478 let mut row = base_row;
1479 row.address_offset = u64::from(op_range);
1480 row.line += u64::from(255 - OPCODE_BASE - op_range * line_range) + 1;
1481 row.line -= u64::from(neg_line_base);
1482 tests.push((
1483 row,
1484 vec![LineInstruction::ConstAddPc, LineInstruction::Copy],
1485 ));
1486
1487 let mut row = base_row;
1488 row.address_offset = u64::from(op_range);
1489 row.line += u64::from(255 - OPCODE_BASE - op_range * line_range) + 2;
1490 row.line -= u64::from(neg_line_base);
1491 tests.push((
1492 row,
1493 vec![
1494 LineInstruction::ConstAddPc,
1495 LineInstruction::Special(OPCODE_BASE + 6),
1496 ],
1497 ));
1498
1499 let mut row = base_row;
1500 row.address_offset = u64::from(op_range) * 2;
1501 row.line += u64::from(255 - OPCODE_BASE - op_range * line_range);
1502 row.line -= u64::from(neg_line_base);
1503 tests.push((
1504 row,
1505 vec![LineInstruction::ConstAddPc, LineInstruction::Special(255)],
1506 ));
1507
1508 let mut row = base_row;
1509 row.address_offset = u64::from(op_range) * 2;
1510 row.line += u64::from(255 - OPCODE_BASE - op_range * line_range) + 1;
1511 row.line -= u64::from(neg_line_base);
1512 tests.push((
1513 row,
1514 vec![
1515 LineInstruction::AdvancePc(row.address_offset),
1516 LineInstruction::Copy,
1517 ],
1518 ));
1519
1520 let mut row = base_row;
1521 row.address_offset = u64::from(op_range) * 2;
1522 row.line += u64::from(255 - OPCODE_BASE - op_range * line_range) + 2;
1523 row.line -= u64::from(neg_line_base);
1524 tests.push((
1525 row,
1526 vec![
1527 LineInstruction::AdvancePc(row.address_offset),
1528 LineInstruction::Special(OPCODE_BASE + 6),
1529 ],
1530 ));
1531
1532 let mut row = base_row;
1533 row.address_offset = 0x1234;
1534 tests.push((
1535 row,
1536 vec![LineInstruction::AdvancePc(0x1234), LineInstruction::Copy],
1537 ));
1538
1539 let mut row = base_row;
1540 row.line += 0x1234;
1541 tests.push((
1542 row,
1543 vec![LineInstruction::AdvanceLine(0x1234), LineInstruction::Copy],
1544 ));
1545
1546 let mut row = base_row;
1547 row.file = file_id;
1548 tests.push((
1549 row,
1550 vec![LineInstruction::SetFile(file_id), LineInstruction::Copy],
1551 ));
1552
1553 let mut row = base_row;
1554 row.column = 0x1234;
1555 tests.push((
1556 row,
1557 vec![LineInstruction::SetColumn(0x1234), LineInstruction::Copy],
1558 ));
1559
1560 let mut row = base_row;
1561 row.discriminator = 0x1234;
1562 tests.push((
1563 row,
1564 vec![
1565 LineInstruction::SetDiscriminator(0x1234),
1566 LineInstruction::Copy,
1567 ],
1568 ));
1569
1570 let mut row = base_row;
1571 row.is_statement = !row.is_statement;
1572 tests.push((
1573 row,
1574 vec![LineInstruction::NegateStatement, LineInstruction::Copy],
1575 ));
1576
1577 let mut row = base_row;
1578 row.basic_block = true;
1579 tests.push((
1580 row,
1581 vec![LineInstruction::SetBasicBlock, LineInstruction::Copy],
1582 ));
1583
1584 let mut row = base_row;
1585 row.prologue_end = true;
1586 tests.push((
1587 row,
1588 vec![LineInstruction::SetPrologueEnd, LineInstruction::Copy],
1589 ));
1590
1591 let mut row = base_row;
1592 row.epilogue_begin = true;
1593 tests.push((
1594 row,
1595 vec![LineInstruction::SetEpilogueBegin, LineInstruction::Copy],
1596 ));
1597
1598 let mut row = base_row;
1599 row.isa = 0x1234;
1600 tests.push((
1601 row,
1602 vec![LineInstruction::SetIsa(0x1234), LineInstruction::Copy],
1603 ));
1604
1605 for test in tests {
1606 // Test generate_row().
1607 let mut program = program.clone();
1608 program.row = test.0;
1609 program.generate_row();
1610 assert_eq!(
1611 &program.instructions[base_instructions.len()..],
1612 &test.1[..]
1613 );
1614
1615 // Test LineProgram::from().
1616 let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian));
1617 let debug_line_offset = program
1618 .write(
1619 &mut debug_line,
1620 encoding,
1621 &debug_line_str_offsets,
1622 &debug_str_offsets,
1623 )
1624 .unwrap();
1625
1626 let read_debug_line =
1627 read::DebugLine::new(debug_line.slice(), LittleEndian);
1628 let read_program = read_debug_line
1629 .program(
1630 debug_line_offset,
1631 address_size,
1632 Some(read::EndianSlice::new(dir1, LittleEndian)),
1633 Some(read::EndianSlice::new(file1, LittleEndian)),
1634 )
1635 .unwrap();
1636
1637 let dwarf = read::Dwarf::default();
1638 let mut convert_line_strings = LineStringTable::default();
1639 let mut convert_strings = StringTable::default();
1640 let (convert_program, _convert_files) = LineProgram::from(
1641 read_program,
1642 &dwarf,
1643 &mut convert_line_strings,
1644 &mut convert_strings,
1645 convert_address,
1646 )
1647 .unwrap();
1648 assert_eq!(
1649 &convert_program.instructions[base_instructions.len()..],
1650 &test.1[..]
1651 );
1652 }
1653 }
1654 }
1655 }
1656 }
1657
1658 #[test]
1659 fn test_line_instruction() {
1660 let dir1 = &b"dir1"[..];
1661 let file1 = &b"file1"[..];
1662
1663 let debug_line_str_offsets = DebugLineStrOffsets::none();
1664 let debug_str_offsets = DebugStrOffsets::none();
1665
1666 for &version in &[2, 3, 4, 5] {
1667 for &address_size in &[4, 8] {
1668 for &format in &[Format::Dwarf32, Format::Dwarf64] {
1669 let encoding = Encoding {
1670 format,
1671 version,
1672 address_size,
1673 };
1674 let mut program = LineProgram::new(
1675 encoding,
1676 LineEncoding::default(),
1677 LineString::String(dir1.to_vec()),
1678 LineString::String(file1.to_vec()),
1679 None,
1680 );
1681 let dir_id = program.default_directory();
1682 let file_id =
1683 program.add_file(LineString::String(file1.to_vec()), dir_id, None);
1684
1685 for (inst, expect_inst) in &[
1686 (
1687 LineInstruction::Special(OPCODE_BASE),
1688 read::LineInstruction::Special(OPCODE_BASE),
1689 ),
1690 (
1691 LineInstruction::Special(255),
1692 read::LineInstruction::Special(255),
1693 ),
1694 (LineInstruction::Copy, read::LineInstruction::Copy),
1695 (
1696 LineInstruction::AdvancePc(0x12),
1697 read::LineInstruction::AdvancePc(0x12),
1698 ),
1699 (
1700 LineInstruction::AdvanceLine(0x12),
1701 read::LineInstruction::AdvanceLine(0x12),
1702 ),
1703 (
1704 LineInstruction::SetFile(file_id),
1705 read::LineInstruction::SetFile(file_id.raw()),
1706 ),
1707 (
1708 LineInstruction::SetColumn(0x12),
1709 read::LineInstruction::SetColumn(0x12),
1710 ),
1711 (
1712 LineInstruction::NegateStatement,
1713 read::LineInstruction::NegateStatement,
1714 ),
1715 (
1716 LineInstruction::SetBasicBlock,
1717 read::LineInstruction::SetBasicBlock,
1718 ),
1719 (
1720 LineInstruction::ConstAddPc,
1721 read::LineInstruction::ConstAddPc,
1722 ),
1723 (
1724 LineInstruction::SetPrologueEnd,
1725 read::LineInstruction::SetPrologueEnd,
1726 ),
1727 (
1728 LineInstruction::SetEpilogueBegin,
1729 read::LineInstruction::SetEpilogueBegin,
1730 ),
1731 (
1732 LineInstruction::SetIsa(0x12),
1733 read::LineInstruction::SetIsa(0x12),
1734 ),
1735 (
1736 LineInstruction::EndSequence,
1737 read::LineInstruction::EndSequence,
1738 ),
1739 (
1740 LineInstruction::SetAddress(Address::Constant(0x12)),
1741 read::LineInstruction::SetAddress(0x12),
1742 ),
1743 (
1744 LineInstruction::SetDiscriminator(0x12),
1745 read::LineInstruction::SetDiscriminator(0x12),
1746 ),
1747 ][..]
1748 {
1749 let mut program = program.clone();
1750 program.instructions.push(*inst);
1751
1752 let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian));
1753 let debug_line_offset = program
1754 .write(
1755 &mut debug_line,
1756 encoding,
1757 &debug_line_str_offsets,
1758 &debug_str_offsets,
1759 )
1760 .unwrap();
1761
1762 let read_debug_line =
1763 read::DebugLine::new(debug_line.slice(), LittleEndian);
1764 let read_program = read_debug_line
1765 .program(
1766 debug_line_offset,
1767 address_size,
1768 Some(read::EndianSlice::new(dir1, LittleEndian)),
1769 Some(read::EndianSlice::new(file1, LittleEndian)),
1770 )
1771 .unwrap();
1772 let read_header = read_program.header();
1773 let mut read_insts = read_header.instructions();
1774 assert_eq!(
1775 *expect_inst,
1776 read_insts.next_instruction(read_header).unwrap().unwrap()
1777 );
1778 assert_eq!(None, read_insts.next_instruction(read_header).unwrap());
1779 }
1780 }
1781 }
1782 }
1783 }
1784
1785 // Test that the address/line advance is correct. We don't test for optimality.
1786 #[test]
1787 fn test_advance() {
1788 let encoding = Encoding {
1789 format: Format::Dwarf32,
1790 version: 4,
1791 address_size: 8,
1792 };
1793
1794 let dir1 = &b"dir1"[..];
1795 let file1 = &b"file1"[..];
1796
1797 let addresses = 0..50;
1798 let lines = -10..25i64;
1799
1800 let debug_line_str_offsets = DebugLineStrOffsets::none();
1801 let debug_str_offsets = DebugStrOffsets::none();
1802
1803 for minimum_instruction_length in [1, 4] {
1804 for maximum_operations_per_instruction in [1, 3] {
1805 for line_base in [-5, 0] {
1806 for line_range in [10, 20] {
1807 let line_encoding = LineEncoding {
1808 minimum_instruction_length,
1809 maximum_operations_per_instruction,
1810 line_base,
1811 line_range,
1812 default_is_stmt: true,
1813 };
1814 let mut program = LineProgram::new(
1815 encoding,
1816 line_encoding,
1817 LineString::String(dir1.to_vec()),
1818 LineString::String(file1.to_vec()),
1819 None,
1820 );
1821 for address_advance in addresses.clone() {
1822 program.begin_sequence(Some(Address::Constant(0x1000)));
1823 program.row().line = 0x10000;
1824 program.generate_row();
1825 for line_advance in lines.clone() {
1826 {
1827 let row = program.row();
1828 row.address_offset +=
1829 address_advance * u64::from(minimum_instruction_length);
1830 row.line = row.line.wrapping_add(line_advance as u64);
1831 }
1832 program.generate_row();
1833 }
1834 let address_offset = program.row().address_offset
1835 + u64::from(minimum_instruction_length);
1836 program.end_sequence(address_offset);
1837 }
1838
1839 let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian));
1840 let debug_line_offset = program
1841 .write(
1842 &mut debug_line,
1843 encoding,
1844 &debug_line_str_offsets,
1845 &debug_str_offsets,
1846 )
1847 .unwrap();
1848
1849 let read_debug_line =
1850 read::DebugLine::new(debug_line.slice(), LittleEndian);
1851 let read_program = read_debug_line
1852 .program(
1853 debug_line_offset,
1854 8,
1855 Some(read::EndianSlice::new(dir1, LittleEndian)),
1856 Some(read::EndianSlice::new(file1, LittleEndian)),
1857 )
1858 .unwrap();
1859
1860 let mut rows = read_program.rows();
1861 for address_advance in addresses.clone() {
1862 let mut address;
1863 let mut line;
1864 {
1865 let row = rows.next_row().unwrap().unwrap().1;
1866 address = row.address();
1867 line = row.line().unwrap().get();
1868 }
1869 assert_eq!(address, 0x1000);
1870 assert_eq!(line, 0x10000);
1871 for line_advance in lines.clone() {
1872 let row = rows.next_row().unwrap().unwrap().1;
1873 assert_eq!(
1874 row.address() - address,
1875 address_advance * u64::from(minimum_instruction_length)
1876 );
1877 assert_eq!(
1878 (row.line().unwrap().get() as i64) - (line as i64),
1879 line_advance
1880 );
1881 address = row.address();
1882 line = row.line().unwrap().get();
1883 }
1884 let row = rows.next_row().unwrap().unwrap().1;
1885 assert!(row.end_sequence());
1886 }
1887 }
1888 }
1889 }
1890 }
1891 }
1892
1893 #[test]
1894 fn test_line_string() {
1895 let version = 5;
1896
1897 let file = b"file1";
1898
1899 let mut strings = StringTable::default();
1900 let string_id = strings.add("file2");
1901 let mut debug_str = DebugStr::from(EndianVec::new(LittleEndian));
1902 let debug_str_offsets = strings.write(&mut debug_str).unwrap();
1903
1904 let mut line_strings = LineStringTable::default();
1905 let line_string_id = line_strings.add("file3");
1906 let mut debug_line_str = DebugLineStr::from(EndianVec::new(LittleEndian));
1907 let debug_line_str_offsets = line_strings.write(&mut debug_line_str).unwrap();
1908
1909 for &address_size in &[4, 8] {
1910 for &format in &[Format::Dwarf32, Format::Dwarf64] {
1911 let encoding = Encoding {
1912 format,
1913 version,
1914 address_size,
1915 };
1916
1917 for (file, expect_file) in [
1918 (
1919 LineString::String(file.to_vec()),
1920 read::AttributeValue::String(read::EndianSlice::new(file, LittleEndian)),
1921 ),
1922 (
1923 LineString::StringRef(string_id),
1924 read::AttributeValue::DebugStrRef(debug_str_offsets.get(string_id)),
1925 ),
1926 (
1927 LineString::LineStringRef(line_string_id),
1928 read::AttributeValue::DebugLineStrRef(
1929 debug_line_str_offsets.get(line_string_id),
1930 ),
1931 ),
1932 ] {
1933 let program = LineProgram::new(
1934 encoding,
1935 LineEncoding::default(),
1936 LineString::String(b"dir".to_vec()),
1937 file,
1938 None,
1939 );
1940
1941 let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian));
1942 let debug_line_offset = program
1943 .write(
1944 &mut debug_line,
1945 encoding,
1946 &debug_line_str_offsets,
1947 &debug_str_offsets,
1948 )
1949 .unwrap();
1950
1951 let read_debug_line = read::DebugLine::new(debug_line.slice(), LittleEndian);
1952 let read_program = read_debug_line
1953 .program(debug_line_offset, address_size, None, None)
1954 .unwrap();
1955 let read_header = read_program.header();
1956 assert_eq!(read_header.file(0).unwrap().path_name(), expect_file);
1957 }
1958 }
1959 }
1960 }
1961
1962 #[test]
1963 fn test_missing_comp_dir() {
1964 let debug_line_str_offsets = DebugLineStrOffsets::none();
1965 let debug_str_offsets = DebugStrOffsets::none();
1966
1967 for &version in &[2, 3, 4, 5] {
1968 for &address_size in &[4, 8] {
1969 for &format in &[Format::Dwarf32, Format::Dwarf64] {
1970 let encoding = Encoding {
1971 format,
1972 version,
1973 address_size,
1974 };
1975 let program = LineProgram::new(
1976 encoding,
1977 LineEncoding::default(),
1978 LineString::String(Vec::new()),
1979 LineString::String(Vec::new()),
1980 None,
1981 );
1982
1983 let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian));
1984 let debug_line_offset = program
1985 .write(
1986 &mut debug_line,
1987 encoding,
1988 &debug_line_str_offsets,
1989 &debug_str_offsets,
1990 )
1991 .unwrap();
1992
1993 let read_debug_line = read::DebugLine::new(debug_line.slice(), LittleEndian);
1994 let read_program = read_debug_line
1995 .program(
1996 debug_line_offset,
1997 address_size,
1998 // Testing missing comp_dir/comp_name.
1999 None,
2000 None,
2001 )
2002 .unwrap();
2003
2004 let dwarf = read::Dwarf::default();
2005 let mut convert_line_strings = LineStringTable::default();
2006 let mut convert_strings = StringTable::default();
2007 let convert_address = &|address| Some(Address::Constant(address));
2008 LineProgram::from(
2009 read_program,
2010 &dwarf,
2011 &mut convert_line_strings,
2012 &mut convert_strings,
2013 convert_address,
2014 )
2015 .unwrap();
2016 }
2017 }
2018 }
2019 }
2020 }