use alloc::vec::Vec;
use core::fmt;
use core::num::Wrapping;
use core::result;
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, ReaderOffset, Result, Section};
#[derive(Debug, Default, Clone, Copy)]
pub struct DebugLine<R> {
debug_line_section: R,
}
impl<'input, Endian> DebugLine<EndianSlice<'input, Endian>>
where
Endian: Endianity,
{
pub fn new(debug_line_section: &'input [u8], endian: Endian) -> Self {
Self::from(EndianSlice::new(debug_line_section, endian))
}
}
impl<R: Reader> DebugLine<R> {
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> {
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(note = "LineNumberProgram has been renamed to LineProgram, use that instead.")]
pub type LineNumberProgram<R, Offset> = dyn LineProgram<R, Offset>;
pub trait LineProgram<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn header(&self) -> &LineProgramHeader<R, Offset>;
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>) {
}
}
#[deprecated(note = "StateMachine has been renamed to LineRows, use that instead.")]
pub type StateMachine<R, Program, Offset> = LineRows<R, Program, Offset>;
#[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,
{
#[allow(clippy::new_ret_no_self)]
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,
}
}
#[inline]
pub fn header(&self) -> &LineProgramHeader<R, Offset> {
self.program.header()
}
pub fn next_row(&mut self) -> Result<Option<(&LineProgramHeader<R, Offset>, &LineRow)>> {
self.row.reset(self.program.header());
loop {
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) {
return Ok(Some((self.header(), &self.row)));
}
}
}
}
}
}
#[deprecated(note = "Opcode has been renamed to LineInstruction, use that instead.")]
pub type Opcode<R> = LineInstruction<R, <R as Reader>::Offset>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineInstruction<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
Special(u8),
Copy,
AdvancePc(u64),
AdvanceLine(i64),
SetFile(u64),
SetColumn(u64),
NegateStatement,
SetBasicBlock,
ConstAddPc,
FixedAddPc(u16),
SetPrologueEnd,
SetEpilogueBegin,
SetIsa(u64),
UnknownStandard0(constants::DwLns),
UnknownStandard1(constants::DwLns, u64),
UnknownStandardN(constants::DwLns, R),
EndSequence,
SetAddress(u64),
DefineFile(FileEntry<R, Offset>),
SetDiscriminator(u64),
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))
}
}
}
}
}
}
}
impl<R, Offset> fmt::Display for LineInstruction<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
match *self {
LineInstruction::Special(opcode) => write!(f, "Special opcode {}", opcode),
LineInstruction::Copy => write!(f, "{}", constants::DW_LNS_copy),
LineInstruction::AdvancePc(advance) => {
write!(f, "{} by {}", constants::DW_LNS_advance_pc, advance)
}
LineInstruction::AdvanceLine(increment) => {
write!(f, "{} by {}", constants::DW_LNS_advance_line, increment)
}
LineInstruction::SetFile(file) => {
write!(f, "{} to {}", constants::DW_LNS_set_file, file)
}
LineInstruction::SetColumn(column) => {
write!(f, "{} to {}", constants::DW_LNS_set_column, column)
}
LineInstruction::NegateStatement => write!(f, "{}", constants::DW_LNS_negate_stmt),
LineInstruction::SetBasicBlock => write!(f, "{}", constants::DW_LNS_set_basic_block),
LineInstruction::ConstAddPc => write!(f, "{}", constants::DW_LNS_const_add_pc),
LineInstruction::FixedAddPc(advance) => {
write!(f, "{} by {}", constants::DW_LNS_fixed_advance_pc, advance)
}
LineInstruction::SetPrologueEnd => write!(f, "{}", constants::DW_LNS_set_prologue_end),
LineInstruction::SetEpilogueBegin => {
write!(f, "{}", constants::DW_LNS_set_epilogue_begin)
}
LineInstruction::SetIsa(isa) => write!(f, "{} to {}", constants::DW_LNS_set_isa, isa),
LineInstruction::UnknownStandard0(opcode) => write!(f, "Unknown {}", opcode),
LineInstruction::UnknownStandard1(opcode, arg) => {
write!(f, "Unknown {} with operand {}", opcode, arg)
}
LineInstruction::UnknownStandardN(opcode, ref args) => {
write!(f, "Unknown {} with operands {:?}", opcode, args)
}
LineInstruction::EndSequence => write!(f, "{}", constants::DW_LNE_end_sequence),
LineInstruction::SetAddress(address) => {
write!(f, "{} to {}", constants::DW_LNE_set_address, address)
}
LineInstruction::DefineFile(_) => write!(f, "{}", constants::DW_LNE_define_file),
LineInstruction::SetDiscriminator(discr) => {
write!(f, "{} to {}", constants::DW_LNE_set_discriminator, discr)
}
LineInstruction::UnknownExtended(opcode, _) => write!(f, "Unknown {}", opcode),
}
}
}
#[deprecated(note = "OpcodesIter has been renamed to LineInstructions, use that instead.")]
pub type OpcodesIter<R> = LineInstructions<R>;
#[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> {
#[allow(clippy::inline_always)]
#[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(note = "LineNumberRow has been renamed to LineRow, use that instead.")]
pub type LineNumberRow = LineRow;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineRow {
address: Wrapping<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 {
pub fn new<R: Reader>(header: &LineProgramHeader<R>) -> Self {
LineRow {
address: Wrapping(0),
op_index: Wrapping(0),
file: 1,
line: Wrapping(1),
column: 0,
is_stmt: header.line_encoding.default_is_stmt,
basic_block: false,
end_sequence: false,
prologue_end: false,
epilogue_begin: false,
isa: 0,
discriminator: 0,
}
}
#[inline]
pub fn address(&self) -> u64 {
self.address.0
}
#[inline]
pub fn op_index(&self) -> u64 {
self.op_index.0
}
#[inline]
pub fn file_index(&self) -> u64 {
self.file
}
#[inline]
pub fn file<'header, R: Reader>(
&self,
header: &'header LineProgramHeader<R>,
) -> Option<&'header FileEntry<R>> {
header.file(self.file)
}
#[inline]
pub fn line(&self) -> Option<u64> {
if self.line.0 == 0 {
None
} else {
Some(self.line.0)
}
}
#[inline]
pub fn column(&self) -> ColumnType {
if self.column == 0 {
ColumnType::LeftEdge
} else {
ColumnType::Column(self.column)
}
}
#[inline]
pub fn is_stmt(&self) -> bool {
self.is_stmt
}
#[inline]
pub fn basic_block(&self) -> bool {
self.basic_block
}
#[inline]
pub fn end_sequence(&self) -> bool {
self.end_sequence
}
#[inline]
pub fn prologue_end(&self) -> bool {
self.prologue_end
}
#[inline]
pub fn epilogue_begin(&self) -> bool {
self.epilogue_begin
}
#[inline]
pub fn isa(&self) -> u64 {
self.isa
}
#[inline]
pub fn discriminator(&self) -> u64 {
self.discriminator
}
#[inline]
pub fn execute<R, Program>(
&mut self,
instruction: LineInstruction<R>,
program: &mut Program,
) -> bool
where
Program: LineProgram<R>,
R: Reader,
{
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) => {
self.address += Wrapping(u64::from(operand));
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) => {
self.address.0 = address;
self.op_index.0 = 0;
false
}
LineInstruction::DefineFile(entry) => {
program.add_file(entry);
false
}
LineInstruction::SetDiscriminator(discriminator) => {
self.discriminator = discriminator;
false
}
LineInstruction::UnknownStandard0(_)
| LineInstruction::UnknownStandard1(_, _)
| LineInstruction::UnknownStandardN(_, _)
| LineInstruction::UnknownExtended(_, _) => false,
}
}
#[inline]
pub fn reset<R: Reader>(&mut self, header: &LineProgramHeader<R>) {
if self.end_sequence {
*self = Self::new(header);
} else {
self.discriminator = 0;
self.basic_block = false;
self.prologue_end = false;
self.epilogue_begin = false;
}
}
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);
}
}
fn apply_operation_advance<R: Reader>(
&mut self,
operation_advance: u64,
header: &LineProgramHeader<R>,
) {
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);
if maximum_operations_per_instruction.0 == 1 {
self.address += minimum_instruction_length * operation_advance;
self.op_index.0 = 0;
} else {
let op_index_with_advance = self.op_index + operation_advance;
self.address += minimum_instruction_length
* (op_index_with_advance / maximum_operations_per_instruction);
self.op_index = op_index_with_advance % maximum_operations_per_instruction;
}
}
#[inline]
fn adjust_opcode<R: Reader>(&self, opcode: u8, header: &LineProgramHeader<R>) -> u8 {
opcode - header.opcode_base
}
fn exec_special_opcode<R: Reader>(&mut self, opcode: u8, header: &LineProgramHeader<R>) {
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;
let line_base = i64::from(header.line_encoding.line_base);
self.apply_line_advance(line_base + i64::from(line_advance));
self.apply_operation_advance(u64::from(operation_advance), header);
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColumnType {
LeftEdge,
Column(u64),
}
#[deprecated(note = "LineNumberSequence has been renamed to LineSequence, use that instead.")]
pub type LineNumberSequence<R> = LineSequence<R>;
#[derive(Clone, Debug)]
pub struct LineSequence<R: Reader> {
pub start: u64,
pub end: u64,
instructions: LineInstructions<R>,
}
#[deprecated(
note = "LineNumberProgramHeader has been renamed to LineProgramHeader, use that instead."
)]
pub type LineNumberProgramHeader<R, Offset> = LineProgramHeader<R, Offset>;
#[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,
header_length: Offset,
line_encoding: LineEncoding,
opcode_base: u8,
standard_opcode_lengths: R,
directory_entry_format: Vec<FileEntryFormat>,
include_directories: Vec<AttributeValue<R, Offset>>,
file_name_entry_format: Vec<FileEntryFormat>,
file_names: Vec<FileEntry<R, Offset>>,
program_buf: R,
comp_dir: Option<R>,
comp_file: Option<FileEntry<R, Offset>>,
}
impl<R, Offset> LineProgramHeader<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
pub fn offset(&self) -> DebugLineOffset<R::Offset> {
self.offset
}
pub fn unit_length(&self) -> R::Offset {
self.unit_length
}
pub fn encoding(&self) -> Encoding {
self.encoding
}
pub fn version(&self) -> u16 {
self.encoding.version
}
pub fn header_length(&self) -> R::Offset {
self.header_length
}
pub fn address_size(&self) -> u8 {
self.encoding.address_size
}
pub fn format(&self) -> Format {
self.encoding.format
}
pub fn line_encoding(&self) -> LineEncoding {
self.line_encoding
}
pub fn minimum_instruction_length(&self) -> u8 {
self.line_encoding.minimum_instruction_length
}
pub fn maximum_operations_per_instruction(&self) -> u8 {
self.line_encoding.maximum_operations_per_instruction
}
pub fn default_is_stmt(&self) -> bool {
self.line_encoding.default_is_stmt
}
pub fn line_base(&self) -> i8 {
self.line_encoding.line_base
}
pub fn line_range(&self) -> u8 {
self.line_encoding.line_range
}
pub fn opcode_base(&self) -> u8 {
self.opcode_base
}
pub fn standard_opcode_lengths(&self) -> &R {
&self.standard_opcode_lengths
}
pub fn directory_entry_format(&self) -> &[FileEntryFormat] {
&self.directory_entry_format[..]
}
pub fn include_directories(&self) -> &[AttributeValue<R, Offset>] {
&self.include_directories[..]
}
pub fn directory(&self, directory: u64) -> Option<AttributeValue<R, Offset>> {
if self.encoding.version <= 4 {
if directory == 0 {
self.comp_dir.clone().map(AttributeValue::String)
} else {
let directory = directory as usize - 1;
self.include_directories.get(directory).cloned()
}
} else {
self.include_directories.get(directory as usize).cloned()
}
}
pub fn file_name_entry_format(&self) -> &[FileEntryFormat] {
&self.file_name_entry_format[..]
}
pub fn file_has_timestamp(&self) -> bool {
self.encoding.version <= 4
|| self
.file_name_entry_format
.iter()
.any(|x| x.content_type == constants::DW_LNCT_timestamp)
}
pub fn file_has_size(&self) -> bool {
self.encoding.version <= 4
|| self
.file_name_entry_format
.iter()
.any(|x| x.content_type == constants::DW_LNCT_size)
}
pub fn file_has_md5(&self) -> bool {
self.file_name_entry_format
.iter()
.any(|x| x.content_type == constants::DW_LNCT_MD5)
}
pub fn file_names(&self) -> &[FileEntry<R, Offset>] {
&self.file_names[..]
}
pub fn file(&self, file: u64) -> Option<&FileEntry<R, Offset>> {
if self.encoding.version <= 4 {
if file == 0 {
self.comp_file.as_ref()
} else {
let file = file as usize - 1;
self.file_names.get(file)
}
} else {
self.file_names.get(file as usize)
}
}
pub fn raw_program_buf(&self) -> R {
self.program_buf.clone()
}
pub fn instructions(&self) -> LineInstructions<R> {
LineInstructions {
input: self.program_buf.clone(),
}
}
fn parse(
input: &mut R,
offset: DebugLineOffset<Offset>,
mut address_size: u8,
mut comp_dir: Option<R>,
comp_name: Option<R>,
) -> Result<LineProgramHeader<R, Offset>> {
let (unit_length, format) = input.read_initial_length()?;
let rest = &mut input.split(unit_length)?;
let version = rest.read_u16()?;
if version < 2 || version > 5 {
return Err(Error::UnknownVersion(u64::from(version)));
}
if version >= 5 {
address_size = rest.read_u8()?;
let segment_selector_size = rest.read_u8()?;
if segment_selector_size != 0 {
return Err(Error::UnsupportedSegmentSize);
}
}
let encoding = Encoding {
format,
version,
address_size,
};
let header_length = rest.read_length(format)?;
let mut program_buf = rest.clone();
program_buf.skip(header_length)?;
rest.truncate(header_length)?;
let minimum_instruction_length = rest.read_u8()?;
if minimum_instruction_length == 0 {
return Err(Error::MinimumInstructionLengthZero);
}
let maximum_operations_per_instruction = if version >= 4 { rest.read_u8()? } else { 1 };
if maximum_operations_per_instruction == 0 {
return Err(Error::MaximumOperationsPerInstructionZero);
}
let default_is_stmt = rest.read_u8()? != 0;
let line_base = rest.read_i8()?;
let line_range = rest.read_u8()?;
if line_range == 0 {
return Err(Error::LineRangeZero);
}
let line_encoding = LineEncoding {
minimum_instruction_length,
maximum_operations_per_instruction,
default_is_stmt,
line_base,
line_range,
};
let opcode_base = rest.read_u8()?;
if opcode_base == 0 {
return Err(Error::OpcodeBaseZero);
}
let standard_opcode_count = R::Offset::from_u8(opcode_base - 1);
let standard_opcode_lengths = rest.split(standard_opcode_count)?;
let directory_entry_format;
let mut include_directories = Vec::new();
if version <= 4 {
directory_entry_format = Vec::new();
loop {
let directory = rest.read_null_terminated_slice()?;
if directory.is_empty() {
break;
}
include_directories.push(AttributeValue::String(directory));
}
} else {
comp_dir = None;
directory_entry_format = FileEntryFormat::parse(rest)?;
let count = rest.read_uleb128()?;
for _ in 0..count {
include_directories.push(parse_directory_v5(
rest,
encoding,
&directory_entry_format,
)?);
}
}
let comp_file;
let file_name_entry_format;
let mut file_names = Vec::new();
if version <= 4 {
comp_file = comp_name.map(|name| FileEntry {
path_name: AttributeValue::String(name),
directory_index: 0,
timestamp: 0,
size: 0,
md5: [0; 16],
});
file_name_entry_format = Vec::new();
loop {
let path_name = rest.read_null_terminated_slice()?;
if path_name.is_empty() {
break;
}
file_names.push(FileEntry::parse(rest, path_name)?);
}
} else {
comp_file = None;
file_name_entry_format = FileEntryFormat::parse(rest)?;
let count = rest.read_uleb128()?;
for _ in 0..count {
file_names.push(parse_file_v5(rest, encoding, &file_name_entry_format)?);
}
}
let header = LineProgramHeader {
encoding,
offset,
unit_length,
header_length,
line_encoding,
opcode_base,
standard_opcode_lengths,
directory_entry_format,
include_directories,
file_name_entry_format,
file_names,
program_buf,
comp_dir,
comp_file,
};
Ok(header)
}
}
#[deprecated(
note = "IncompleteLineNumberProgram has been renamed to IncompleteLineProgram, use that instead."
)]
pub type IncompleteLineNumberProgram<R, Offset> = IncompleteLineProgram<R, Offset>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IncompleteLineProgram<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
header: LineProgramHeader<R, Offset>,
}
impl<R, Offset> IncompleteLineProgram<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
pub fn header(&self) -> &LineProgramHeader<R, Offset> {
&self.header
}
pub fn rows(self) -> OneShotLineRows<R, Offset> {
OneShotLineRows::new(self)
}
#[allow(clippy::type_complexity)]
pub fn sequences(self) -> Result<(CompleteLineProgram<R, Offset>, Vec<LineSequence<R>>)> {
let mut sequences = Vec::new();
let mut rows = self.rows();
let mut instructions = rows.instructions.clone();
let mut sequence_start_addr = None;
loop {
let sequence_end_addr;
if rows.next_row()?.is_none() {
break;
}
let row = &rows.row;
if row.end_sequence() {
sequence_end_addr = row.address();
} else if sequence_start_addr.is_none() {
sequence_start_addr = Some(row.address());
continue;
} else {
continue;
}
sequences.push(LineSequence {
start: sequence_start_addr.unwrap_or(0),
end: sequence_end_addr,
instructions: instructions.remove_trailing(&rows.instructions)?,
});
sequence_start_addr = None;
instructions = rows.instructions.clone();
}
let program = CompleteLineProgram {
header: rows.program.header,
};
Ok((program, sequences))
}
}
#[deprecated(
note = "CompleteLineNumberProgram has been renamed to CompleteLineProgram, use that instead."
)]
pub type CompleteLineNumberProgram<R, Offset> = CompleteLineProgram<R, Offset>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompleteLineProgram<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
header: LineProgramHeader<R, Offset>,
}
impl<R, Offset> CompleteLineProgram<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
pub fn header(&self) -> &LineProgramHeader<R, Offset> {
&self.header
}
pub fn resume_from<'program>(
&'program self,
sequence: &LineSequence<R>,
) -> ResumedLineRows<'program, R, Offset> {
ResumedLineRows::resume(self, sequence)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct FileEntry<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
path_name: AttributeValue<R, Offset>,
directory_index: u64,
timestamp: u64,
size: u64,
md5: [u8; 16],
}
impl<R, Offset> FileEntry<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
fn parse(input: &mut R, path_name: R) -> Result<FileEntry<R, Offset>> {
let directory_index = input.read_uleb128()?;
let timestamp = input.read_uleb128()?;
let size = input.read_uleb128()?;
let entry = FileEntry {
path_name: AttributeValue::String(path_name),
directory_index,
timestamp,
size,
md5: [0; 16],
};
Ok(entry)
}
pub fn path_name(&self) -> AttributeValue<R, Offset> {
self.path_name.clone()
}
pub fn directory_index(&self) -> u64 {
self.directory_index
}
pub fn directory(&self, header: &LineProgramHeader<R>) -> Option<AttributeValue<R, Offset>> {
header.directory(self.directory_index)
}
pub fn timestamp(&self) -> u64 {
self.timestamp
}
#[doc(hidden)]
pub fn last_modification(&self) -> u64 {
self.timestamp
}
pub fn size(&self) -> u64 {
self.size
}
#[doc(hidden)]
pub fn length(&self) -> u64 {
self.size
}
pub fn md5(&self) -> &[u8; 16] {
&self.md5
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct FileEntryFormat {
pub content_type: constants::DwLnct,
pub form: constants::DwForm,
}
impl FileEntryFormat {
fn parse<R: Reader>(input: &mut R) -> Result<Vec<FileEntryFormat>> {
let format_count = input.read_u8()? as usize;
let mut format = Vec::with_capacity(format_count);
let mut path_count = 0;
for _ in 0..format_count {
let content_type = input.read_uleb128()?;
let content_type = if content_type > u64::from(u16::max_value()) {
constants::DwLnct(u16::max_value())
} else {
constants::DwLnct(content_type as u16)
};
if content_type == constants::DW_LNCT_path {
path_count += 1;
}
let form = constants::DwForm(input.read_uleb128_u16()?);
format.push(FileEntryFormat { content_type, form });
}
if path_count != 1 {
return Err(Error::MissingFileEntryFormatPath);
}
Ok(format)
}
}
fn parse_directory_v5<R: Reader>(
input: &mut R,
encoding: Encoding,
formats: &[FileEntryFormat],
) -> Result<AttributeValue<R>> {
let mut path_name = None;
for format in formats {
let value = parse_attribute(input, encoding, format.form)?;
if format.content_type == constants::DW_LNCT_path {
path_name = Some(value);
}
}
Ok(path_name.unwrap())
}
fn parse_file_v5<R: Reader>(
input: &mut R,
encoding: Encoding,
formats: &[FileEntryFormat],
) -> Result<FileEntry<R>> {
let mut path_name = None;
let mut directory_index = 0;
let mut timestamp = 0;
let mut size = 0;
let mut md5 = [0; 16];
for format in formats {
let value = parse_attribute(input, encoding, format.form)?;
match format.content_type {
constants::DW_LNCT_path => path_name = Some(value),
constants::DW_LNCT_directory_index => {
if let Some(value) = value.udata_value() {
directory_index = value;
}
}
constants::DW_LNCT_timestamp => {
if let Some(value) = value.udata_value() {
timestamp = value;
}
}
constants::DW_LNCT_size => {
if let Some(value) = value.udata_value() {
size = value;
}
}
constants::DW_LNCT_MD5 => {
if let AttributeValue::Block(mut value) = value {
if value.len().into_u64() == 16 {
md5 = value.read_u8_array()?;
}
}
}
_ => {}
}
}
Ok(FileEntry {
path_name: path_name.unwrap(),
directory_index,
timestamp,
size,
md5,
})
}
fn parse_attribute<R: Reader>(
input: &mut R,
encoding: Encoding,
form: constants::DwForm,
) -> Result<AttributeValue<R>> {
Ok(match form {
constants::DW_FORM_block1 => {
let len = input.read_u8().map(R::Offset::from_u8)?;
let block = input.split(len)?;
AttributeValue::Block(block)
}
constants::DW_FORM_block2 => {
let len = input.read_u16().map(R::Offset::from_u16)?;
let block = input.split(len)?;
AttributeValue::Block(block)
}
constants::DW_FORM_block4 => {
let len = input.read_u32().map(R::Offset::from_u32)?;
let block = input.split(len)?;
AttributeValue::Block(block)
}
constants::DW_FORM_block => {
let len = input.read_uleb128().and_then(R::Offset::from_u64)?;
let block = input.split(len)?;
AttributeValue::Block(block)
}
constants::DW_FORM_data1 => {
let data = input.read_u8()?;
AttributeValue::Data1(data)
}
constants::DW_FORM_data2 => {
let data = input.read_u16()?;
AttributeValue::Data2(data)
}
constants::DW_FORM_data4 => {
let data = input.read_u32()?;
AttributeValue::Data4(data)
}
constants::DW_FORM_data8 => {
let data = input.read_u64()?;
AttributeValue::Data8(data)
}
constants::DW_FORM_data16 => {
let block = input.split(R::Offset::from_u8(16))?;
AttributeValue::Block(block)
}
constants::DW_FORM_udata => {
let data = input.read_uleb128()?;
AttributeValue::Udata(data)
}
constants::DW_FORM_sdata => {
let data = input.read_sleb128()?;
AttributeValue::Sdata(data)
}
constants::DW_FORM_flag => {
let present = input.read_u8()?;
AttributeValue::Flag(present != 0)
}
constants::DW_FORM_sec_offset => {
let offset = input.read_offset(encoding.format)?;
AttributeValue::SecOffset(offset)
}
constants::DW_FORM_string => {
let string = input.read_null_terminated_slice()?;
AttributeValue::String(string)
}
constants::DW_FORM_strp => {
let offset = input.read_offset(encoding.format)?;
AttributeValue::DebugStrRef(DebugStrOffset(offset))
}
constants::DW_FORM_strp_sup | constants::DW_FORM_GNU_strp_alt => {
let offset = input.read_offset(encoding.format)?;
AttributeValue::DebugStrRefSup(DebugStrOffset(offset))
}
constants::DW_FORM_line_strp => {
let offset = input.read_offset(encoding.format)?;
AttributeValue::DebugLineStrRef(DebugLineStrOffset(offset))
}
constants::DW_FORM_strx | constants::DW_FORM_GNU_str_index => {
let index = input.read_uleb128().and_then(R::Offset::from_u64)?;
AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
}
constants::DW_FORM_strx1 => {
let index = input.read_u8().map(R::Offset::from_u8)?;
AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
}
constants::DW_FORM_strx2 => {
let index = input.read_u16().map(R::Offset::from_u16)?;
AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
}
constants::DW_FORM_strx3 => {
let index = input.read_uint(3).and_then(R::Offset::from_u64)?;
AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
}
constants::DW_FORM_strx4 => {
let index = input.read_u32().map(R::Offset::from_u32)?;
AttributeValue::DebugStrOffsetsIndex(DebugStrOffsetsIndex(index))
}
_ => {
return Err(Error::UnknownForm);
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants;
use crate::endianity::LittleEndian;
use crate::read::{EndianSlice, Error};
use crate::test_util::GimliSectionMethods;
use core::u64;
use core::u8;
use test_assembler::{Endian, Label, LabelMaker, Section};
#[test]
fn test_parse_debug_line_32_ok() {
#[rustfmt::skip]
let buf = [
0x3e, 0x00, 0x00, 0x00,
0x04, 0x00,
0x28, 0x00, 0x00, 0x00,
0x01,
0x01,
0x01,
0x00,
0x01,
0x03,
0x01, 0x02,
0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
0x00,
0x00,
0x00,
0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
0x01,
0x00,
0x00,
0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
];
let rest = &mut EndianSlice::new(&buf, LittleEndian);
let comp_dir = EndianSlice::new(b"/comp_dir", LittleEndian);
let comp_name = EndianSlice::new(b"/comp_name", LittleEndian);
let header =
LineProgramHeader::parse(rest, DebugLineOffset(0), 4, Some(comp_dir), Some(comp_name))
.expect("should parse header ok");
assert_eq!(
*rest,
EndianSlice::new(&buf[buf.len() - 16..], LittleEndian)
);
assert_eq!(header.offset, DebugLineOffset(0));
assert_eq!(header.version(), 4);
assert_eq!(header.minimum_instruction_length(), 1);
assert_eq!(header.maximum_operations_per_instruction(), 1);
assert_eq!(header.default_is_stmt(), true);
assert_eq!(header.line_base(), 0);
assert_eq!(header.line_range(), 1);
assert_eq!(header.opcode_base(), 3);
assert_eq!(header.directory(0), Some(AttributeValue::String(comp_dir)));
assert_eq!(
header.file(0).unwrap().path_name,
AttributeValue::String(comp_name)
);
let expected_lengths = [1, 2];
assert_eq!(header.standard_opcode_lengths().slice(), &expected_lengths);
let expected_include_directories = [
AttributeValue::String(EndianSlice::new(b"/inc", LittleEndian)),
AttributeValue::String(EndianSlice::new(b"/inc2", LittleEndian)),
];
assert_eq!(header.include_directories(), &expected_include_directories);
let expected_file_names = [
FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"foo.rs", LittleEndian)),
directory_index: 0,
timestamp: 0,
size: 0,
md5: [0; 16],
},
FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"bar.h", LittleEndian)),
directory_index: 1,
timestamp: 0,
size: 0,
md5: [0; 16],
},
];
assert_eq!(&*header.file_names(), &expected_file_names);
}
#[test]
fn test_parse_debug_line_header_length_too_short() {
#[rustfmt::skip]
let buf = [
0x3e, 0x00, 0x00, 0x00,
0x04, 0x00,
0x15, 0x00, 0x00, 0x00,
0x01,
0x01,
0x01,
0x00,
0x01,
0x03,
0x01, 0x02,
0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
0x00,
0x00,
0x00,
0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
0x01,
0x00,
0x00,
0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
];
let input = &mut EndianSlice::new(&buf, LittleEndian);
match LineProgramHeader::parse(input, DebugLineOffset(0), 4, None, None) {
Err(Error::UnexpectedEof(_)) => return,
otherwise => panic!("Unexpected result: {:?}", otherwise),
}
}
#[test]
fn test_parse_debug_line_unit_length_too_short() {
#[rustfmt::skip]
let buf = [
0x28, 0x00, 0x00, 0x00,
0x04, 0x00,
0x28, 0x00, 0x00, 0x00,
0x01,
0x01,
0x01,
0x00,
0x01,
0x03,
0x01, 0x02,
0x2f, 0x69, 0x6e, 0x63, 0x00, 0x2f, 0x69, 0x6e, 0x63, 0x32, 0x00, 0x00,
0x66, 0x6f, 0x6f, 0x2e, 0x72, 0x73, 0x00,
0x00,
0x00,
0x00,
0x62, 0x61, 0x72, 0x2e, 0x68, 0x00,
0x01,
0x00,
0x00,
0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
];
let input = &mut EndianSlice::new(&buf, LittleEndian);
match LineProgramHeader::parse(input, DebugLineOffset(0), 4, None, None) {
Err(Error::UnexpectedEof(_)) => return,
otherwise => panic!("Unexpected result: {:?}", otherwise),
}
}
const OPCODE_BASE: u8 = 13;
const STANDARD_OPCODE_LENGTHS: &[u8] = &[0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1];
fn make_test_header(
buf: EndianSlice<LittleEndian>,
) -> LineProgramHeader<EndianSlice<LittleEndian>> {
let encoding = Encoding {
format: Format::Dwarf32,
version: 4,
address_size: 8,
};
let line_encoding = LineEncoding {
line_base: -3,
line_range: 12,
..Default::default()
};
LineProgramHeader {
encoding,
offset: DebugLineOffset(0),
unit_length: 1,
header_length: 1,
line_encoding,
opcode_base: OPCODE_BASE,
standard_opcode_lengths: EndianSlice::new(STANDARD_OPCODE_LENGTHS, LittleEndian),
file_names: vec![
FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"foo.c", LittleEndian)),
directory_index: 0,
timestamp: 0,
size: 0,
md5: [0; 16],
},
FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"bar.rs", LittleEndian)),
directory_index: 0,
timestamp: 0,
size: 0,
md5: [0; 16],
},
],
include_directories: vec![],
directory_entry_format: vec![],
file_name_entry_format: vec![],
program_buf: buf,
comp_dir: None,
comp_file: None,
}
}
fn make_test_program(
buf: EndianSlice<LittleEndian>,
) -> IncompleteLineProgram<EndianSlice<LittleEndian>> {
IncompleteLineProgram {
header: make_test_header(buf),
}
}
#[test]
fn test_parse_special_opcodes() {
for i in OPCODE_BASE..u8::MAX {
let input = [i, 0, 0, 0];
let input = EndianSlice::new(&input, LittleEndian);
let header = make_test_header(input);
let mut rest = input;
let opcode =
LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
assert_eq!(*rest, *input.range_from(1..));
assert_eq!(opcode, LineInstruction::Special(i));
}
}
#[test]
fn test_parse_standard_opcodes() {
fn test<Operands>(
raw: constants::DwLns,
operands: Operands,
expected: LineInstruction<EndianSlice<LittleEndian>>,
) where
Operands: AsRef<[u8]>,
{
let mut input = Vec::new();
input.push(raw.0);
input.extend_from_slice(operands.as_ref());
let expected_rest = [0, 1, 2, 3, 4];
input.extend_from_slice(&expected_rest);
let input = EndianSlice::new(&*input, LittleEndian);
let header = make_test_header(input);
let mut rest = input;
let opcode =
LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
assert_eq!(opcode, expected);
assert_eq!(*rest, expected_rest);
}
test(constants::DW_LNS_copy, [], LineInstruction::Copy);
test(
constants::DW_LNS_advance_pc,
[42],
LineInstruction::AdvancePc(42),
);
test(
constants::DW_LNS_advance_line,
[9],
LineInstruction::AdvanceLine(9),
);
test(constants::DW_LNS_set_file, [7], LineInstruction::SetFile(7));
test(
constants::DW_LNS_set_column,
[1],
LineInstruction::SetColumn(1),
);
test(
constants::DW_LNS_negate_stmt,
[],
LineInstruction::NegateStatement,
);
test(
constants::DW_LNS_set_basic_block,
[],
LineInstruction::SetBasicBlock,
);
test(
constants::DW_LNS_const_add_pc,
[],
LineInstruction::ConstAddPc,
);
test(
constants::DW_LNS_fixed_advance_pc,
[42, 0],
LineInstruction::FixedAddPc(42),
);
test(
constants::DW_LNS_set_prologue_end,
[],
LineInstruction::SetPrologueEnd,
);
test(
constants::DW_LNS_set_isa,
[57 + 0x80, 100],
LineInstruction::SetIsa(12857),
);
}
#[test]
fn test_parse_unknown_standard_opcode_no_args() {
let input = [OPCODE_BASE, 1, 2, 3];
let input = EndianSlice::new(&input, LittleEndian);
let mut standard_opcode_lengths = Vec::new();
let mut header = make_test_header(input);
standard_opcode_lengths.extend(header.standard_opcode_lengths.slice());
standard_opcode_lengths.push(0);
header.opcode_base += 1;
header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian);
let mut rest = input;
let opcode =
LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
assert_eq!(
opcode,
LineInstruction::UnknownStandard0(constants::DwLns(OPCODE_BASE))
);
assert_eq!(*rest, *input.range_from(1..));
}
#[test]
fn test_parse_unknown_standard_opcode_one_arg() {
let input = [OPCODE_BASE, 1, 2, 3];
let input = EndianSlice::new(&input, LittleEndian);
let mut standard_opcode_lengths = Vec::new();
let mut header = make_test_header(input);
standard_opcode_lengths.extend(header.standard_opcode_lengths.slice());
standard_opcode_lengths.push(1);
header.opcode_base += 1;
header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian);
let mut rest = input;
let opcode =
LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
assert_eq!(
opcode,
LineInstruction::UnknownStandard1(constants::DwLns(OPCODE_BASE), 1)
);
assert_eq!(*rest, *input.range_from(2..));
}
#[test]
fn test_parse_unknown_standard_opcode_many_args() {
let input = [OPCODE_BASE, 1, 2, 3];
let input = EndianSlice::new(&input, LittleEndian);
let args = EndianSlice::new(&input[1..], LittleEndian);
let mut standard_opcode_lengths = Vec::new();
let mut header = make_test_header(input);
standard_opcode_lengths.extend(header.standard_opcode_lengths.slice());
standard_opcode_lengths.push(3);
header.opcode_base += 1;
header.standard_opcode_lengths = EndianSlice::new(&standard_opcode_lengths, LittleEndian);
let mut rest = input;
let opcode =
LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
assert_eq!(
opcode,
LineInstruction::UnknownStandardN(constants::DwLns(OPCODE_BASE), args)
);
assert_eq!(*rest, []);
}
#[test]
fn test_parse_extended_opcodes() {
fn test<Operands>(
raw: constants::DwLne,
operands: Operands,
expected: LineInstruction<EndianSlice<LittleEndian>>,
) where
Operands: AsRef<[u8]>,
{
let mut input = Vec::new();
input.push(0);
let operands = operands.as_ref();
input.push(1 + operands.len() as u8);
input.push(raw.0);
input.extend_from_slice(operands);
let expected_rest = [0, 1, 2, 3, 4];
input.extend_from_slice(&expected_rest);
let input = EndianSlice::new(&input, LittleEndian);
let header = make_test_header(input);
let mut rest = input;
let opcode =
LineInstruction::parse(&header, &mut rest).expect("Should parse the opcode OK");
assert_eq!(opcode, expected);
assert_eq!(*rest, expected_rest);
}
test(
constants::DW_LNE_end_sequence,
[],
LineInstruction::EndSequence,
);
test(
constants::DW_LNE_set_address,
[1, 2, 3, 4, 5, 6, 7, 8],
LineInstruction::SetAddress(578_437_695_752_307_201),
);
test(
constants::DW_LNE_set_discriminator,
[42],
LineInstruction::SetDiscriminator(42),
);
let mut file = Vec::new();
let path_name = [b'f', b'o', b'o', b'.', b'c', 0];
file.extend_from_slice(&path_name);
file.push(0);
file.push(1);
file.push(2);
test(
constants::DW_LNE_define_file,
file,
LineInstruction::DefineFile(FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"foo.c", LittleEndian)),
directory_index: 0,
timestamp: 1,
size: 2,
md5: [0; 16],
}),
);
let operands = [1, 2, 3, 4, 5, 6];
let opcode = constants::DwLne(99);
test(
opcode,
operands,
LineInstruction::UnknownExtended(opcode, EndianSlice::new(&operands, LittleEndian)),
);
}
#[test]
fn test_file_entry_directory() {
let path_name = [b'f', b'o', b'o', b'.', b'r', b's', 0];
let mut file = FileEntry {
path_name: AttributeValue::String(EndianSlice::new(&path_name, LittleEndian)),
directory_index: 1,
timestamp: 0,
size: 0,
md5: [0; 16],
};
let mut header = make_test_header(EndianSlice::new(&[], LittleEndian));
let dir = AttributeValue::String(EndianSlice::new(b"dir", LittleEndian));
header.include_directories.push(dir);
assert_eq!(file.directory(&header), Some(dir));
file.directory_index = 0;
assert_eq!(file.directory(&header), None);
}
fn assert_exec_opcode<'input>(
header: LineProgramHeader<EndianSlice<'input, LittleEndian>>,
mut registers: LineRow,
opcode: LineInstruction<EndianSlice<'input, LittleEndian>>,
expected_registers: LineRow,
expect_new_row: bool,
) {
let mut program = IncompleteLineProgram { header };
let is_new_row = registers.execute(opcode, &mut program);
assert_eq!(is_new_row, expect_new_row);
assert_eq!(registers, expected_registers);
}
#[test]
fn test_exec_special_noop() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::Special(16);
let expected_registers = initial_registers;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_special_negative_line_advance() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.line.0 = 10;
let opcode = LineInstruction::Special(13);
let mut expected_registers = initial_registers;
expected_registers.line.0 -= 3;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_special_positive_line_advance() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::Special(19);
let mut expected_registers = initial_registers;
expected_registers.line.0 += 3;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_special_positive_address_advance() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::Special(52);
let mut expected_registers = initial_registers;
expected_registers.address.0 += 3;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_special_positive_address_and_line_advance() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::Special(55);
let mut expected_registers = initial_registers;
expected_registers.address.0 += 3;
expected_registers.line.0 += 3;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_special_positive_address_and_negative_line_advance() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.line.0 = 10;
let opcode = LineInstruction::Special(49);
let mut expected_registers = initial_registers;
expected_registers.address.0 += 3;
expected_registers.line.0 -= 3;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_special_line_underflow() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.line.0 = 2;
let opcode = LineInstruction::Special(13);
let mut expected_registers = initial_registers;
expected_registers.line.0 = 0;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_copy() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.address.0 = 1337;
initial_registers.line.0 = 42;
let opcode = LineInstruction::Copy;
let expected_registers = initial_registers;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_advance_pc() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::AdvancePc(42);
let mut expected_registers = initial_registers;
expected_registers.address.0 += 42;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_advance_pc_overflow() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let opcode = LineInstruction::AdvancePc(42);
let mut initial_registers = LineRow::new(&header);
initial_registers.address.0 = u64::MAX;
let mut expected_registers = initial_registers;
expected_registers.address.0 = 41;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_advance_line() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::AdvanceLine(42);
let mut expected_registers = initial_registers;
expected_registers.line.0 += 42;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_advance_line_overflow() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let opcode = LineInstruction::AdvanceLine(42);
let mut initial_registers = LineRow::new(&header);
initial_registers.line.0 = u64::MAX;
let mut expected_registers = initial_registers;
expected_registers.line.0 = 41;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_set_file_in_bounds() {
for file_idx in 1..3 {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::SetFile(file_idx);
let mut expected_registers = initial_registers;
expected_registers.file = file_idx;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
}
#[test]
fn test_exec_set_file_out_of_bounds() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::SetFile(100);
let mut expected_registers = initial_registers;
expected_registers.file = 100;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_file_entry_file_index_out_of_bounds() {
let out_of_bounds_indices = [0, 100];
for file_idx in &out_of_bounds_indices[..] {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut row = LineRow::new(&header);
row.file = *file_idx;
assert_eq!(row.file(&header), None);
}
}
#[test]
fn test_file_entry_file_index_in_bounds() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut row = LineRow::new(&header);
row.file = 2;
assert_eq!(row.file(&header), Some(&header.file_names()[1]));
}
#[test]
fn test_exec_set_column() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::SetColumn(42);
let mut expected_registers = initial_registers;
expected_registers.column = 42;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_negate_statement() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::NegateStatement;
let mut expected_registers = initial_registers;
expected_registers.is_stmt = !initial_registers.is_stmt;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_set_basic_block() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.basic_block = false;
let opcode = LineInstruction::SetBasicBlock;
let mut expected_registers = initial_registers;
expected_registers.basic_block = true;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_const_add_pc() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::ConstAddPc;
let mut expected_registers = initial_registers;
expected_registers.address.0 += 20;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_fixed_add_pc() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.op_index.0 = 1;
let opcode = LineInstruction::FixedAddPc(10);
let mut expected_registers = initial_registers;
expected_registers.address.0 += 10;
expected_registers.op_index.0 = 0;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_set_prologue_end() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let mut initial_registers = LineRow::new(&header);
initial_registers.prologue_end = false;
let opcode = LineInstruction::SetPrologueEnd;
let mut expected_registers = initial_registers;
expected_registers.prologue_end = true;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_set_isa() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::SetIsa(1993);
let mut expected_registers = initial_registers;
expected_registers.isa = 1993;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_unknown_standard_0() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::UnknownStandard0(constants::DwLns(111));
let expected_registers = initial_registers;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_unknown_standard_1() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::UnknownStandard1(constants::DwLns(111), 2);
let expected_registers = initial_registers;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_unknown_standard_n() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::UnknownStandardN(
constants::DwLns(111),
EndianSlice::new(&[2, 2, 2], LittleEndian),
);
let expected_registers = initial_registers;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_end_sequence() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::EndSequence;
let mut expected_registers = initial_registers;
expected_registers.end_sequence = true;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, true);
}
#[test]
fn test_exec_set_address() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::SetAddress(3030);
let mut expected_registers = initial_registers;
expected_registers.address.0 = 3030;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_define_file() {
let mut program = make_test_program(EndianSlice::new(&[], LittleEndian));
let mut row = LineRow::new(program.header());
let file = FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"test.cpp", LittleEndian)),
directory_index: 0,
timestamp: 0,
size: 0,
md5: [0; 16],
};
let opcode = LineInstruction::DefineFile(file);
let is_new_row = row.execute(opcode, &mut program);
assert_eq!(is_new_row, false);
assert_eq!(Some(&file), program.header().file_names.last());
}
#[test]
fn test_exec_set_discriminator() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::SetDiscriminator(9);
let mut expected_registers = initial_registers;
expected_registers.discriminator = 9;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[test]
fn test_exec_unknown_extended() {
let header = make_test_header(EndianSlice::new(&[], LittleEndian));
let initial_registers = LineRow::new(&header);
let opcode = LineInstruction::UnknownExtended(
constants::DwLne(74),
EndianSlice::new(&[], LittleEndian),
);
let expected_registers = initial_registers;
assert_exec_opcode(header, initial_registers, opcode, expected_registers, false);
}
#[allow(dead_code, unreachable_code, unused_variables)]
fn test_line_rows_variance<'a, 'b>(_: &'a [u8], _: &'b [u8])
where
'a: 'b,
{
let a: &OneShotLineRows<EndianSlice<'a, LittleEndian>> = unimplemented!();
let _: &OneShotLineRows<EndianSlice<'b, LittleEndian>> = a;
}
#[test]
fn test_parse_debug_line_v5_ok() {
let expected_lengths = &[1, 2];
let expected_program = &[0, 1, 2, 3, 4];
let expected_rest = &[5, 6, 7, 8, 9];
let expected_include_directories = [
AttributeValue::String(EndianSlice::new(b"dir1", LittleEndian)),
AttributeValue::String(EndianSlice::new(b"dir2", LittleEndian)),
];
let expected_file_names = [
FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"file1", LittleEndian)),
directory_index: 0,
timestamp: 0,
size: 0,
md5: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
},
FileEntry {
path_name: AttributeValue::String(EndianSlice::new(b"file2", LittleEndian)),
directory_index: 1,
timestamp: 0,
size: 0,
md5: [
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
],
},
];
for format in vec![Format::Dwarf32, Format::Dwarf64] {
let length = Label::new();
let header_length = Label::new();
let start = Label::new();
let header_start = Label::new();
let end = Label::new();
let header_end = Label::new();
let section = Section::with_endian(Endian::Little)
.initial_length(format, &length, &start)
.D16(5)
.D8(4)
.D8(0)
.word_label(format.word_size(), &header_length)
.mark(&header_start)
.D8(1)
.D8(1)
.D8(1)
.D8(0)
.D8(1)
.D8(expected_lengths.len() as u8 + 1)
.append_bytes(expected_lengths)
.D8(1)
.uleb(constants::DW_LNCT_path.0 as u64)
.uleb(constants::DW_FORM_string.0 as u64)
.D8(2)
.append_bytes(b"dir1\0")
.append_bytes(b"dir2\0")
.D8(3)
.uleb(constants::DW_LNCT_path.0 as u64)
.uleb(constants::DW_FORM_string.0 as u64)
.uleb(constants::DW_LNCT_directory_index.0 as u64)
.uleb(constants::DW_FORM_data1.0 as u64)
.uleb(constants::DW_LNCT_MD5.0 as u64)
.uleb(constants::DW_FORM_data16.0 as u64)
.D8(2)
.append_bytes(b"file1\0")
.D8(0)
.append_bytes(&expected_file_names[0].md5)
.append_bytes(b"file2\0")
.D8(1)
.append_bytes(&expected_file_names[1].md5)
.mark(&header_end)
.append_bytes(expected_program)
.mark(&end)
.append_bytes(expected_rest);
length.set_const((&end - &start) as u64);
header_length.set_const((&header_end - &header_start) as u64);
let section = section.get_contents().unwrap();
let input = &mut EndianSlice::new(§ion, LittleEndian);
let header = LineProgramHeader::parse(input, DebugLineOffset(0), 0, None, None)
.expect("should parse header ok");
assert_eq!(header.raw_program_buf().slice(), expected_program);
assert_eq!(input.slice(), expected_rest);
assert_eq!(header.offset, DebugLineOffset(0));
assert_eq!(header.version(), 5);
assert_eq!(header.address_size(), 4);
assert_eq!(header.minimum_instruction_length(), 1);
assert_eq!(header.maximum_operations_per_instruction(), 1);
assert_eq!(header.default_is_stmt(), true);
assert_eq!(header.line_base(), 0);
assert_eq!(header.line_range(), 1);
assert_eq!(header.opcode_base(), expected_lengths.len() as u8 + 1);
assert_eq!(header.standard_opcode_lengths().slice(), expected_lengths);
assert_eq!(
header.directory_entry_format(),
&[FileEntryFormat {
content_type: constants::DW_LNCT_path,
form: constants::DW_FORM_string,
}]
);
assert_eq!(header.include_directories(), expected_include_directories);
assert_eq!(header.directory(0), Some(expected_include_directories[0]));
assert_eq!(
header.file_name_entry_format(),
&[
FileEntryFormat {
content_type: constants::DW_LNCT_path,
form: constants::DW_FORM_string,
},
FileEntryFormat {
content_type: constants::DW_LNCT_directory_index,
form: constants::DW_FORM_data1,
},
FileEntryFormat {
content_type: constants::DW_LNCT_MD5,
form: constants::DW_FORM_data16,
}
]
);
assert_eq!(header.file_names(), expected_file_names);
assert_eq!(header.file(0), Some(&expected_file_names[0]));
}
}
}