1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#![no_std]
#![forbid(unsafe_code)]

#[macro_use]
extern crate bitflags;

macro_rules! read_int {
    ($slice:expr, $encoding:expr, $ty:ty) => {{
        use core::{mem, convert::TryFrom};
        let a = TryFrom::try_from(&$slice[..mem::size_of::<$ty>()]).unwrap();
        match $encoding {
            &Encoding::Little => <$ty>::from_le_bytes(a),
            &Encoding::Big => <$ty>::from_be_bytes(a),
        }
    }};
}

mod common;
pub use self::common::{Address, Offset, Error, UnexpectedSize};

mod header;
use self::header::Header;
pub use self::header::{Class, Encoding, Abi, Type, Machine};

mod section;
use self::section::SectionHeader;
pub use self::section::{Index, SectionType, SectionFlags};

mod program;
use self::program::{ProgramType, ProgramHeader};
pub use self::program::ProgramFlags;

mod symbol;
pub use self::symbol::{SymbolBinding, SymbolType, SymbolInfo, SymbolEntry};

mod rel_rela;
pub use self::rel_rela::{RelEntry, RelaEntry};

mod string_note;
pub use self::string_note::{StringTable, NoteEntry, NoteTable};

mod table;
pub use self::table::{Entry, Table};

#[derive(Clone)]
pub struct Elf64<'a> {
    raw: &'a [u8],
    header: Header,
    program_table: Table<'a, ProgramHeader>,
    section_table: Table<'a, SectionHeader>,
    names: Option<StringTable<'a>>,
}

impl<'a> Elf64<'a> {
    pub fn new(raw: &'a [u8]) -> Result<Self, Error> {
        if raw.len() < Header::SIZE {
            return Err(Error::SliceTooShort);
        };

        let header = Header::new(&raw[0..Header::SIZE])?;
        let program_table = header.program_header_table(raw)?;

        let section_table = header.section_header_table(raw)?;
        let names = match header.section_names {
            Index::Regular(i) => {
                let names_section = section_table.pick(i as usize)?;
                match names_section.ty {
                    SectionType::StringTable => {
                        let start = names_section.offset as usize;
                        let end = start + names_section.size as usize;
                        Some(StringTable::new(&raw[start..end]))
                    },
                    _ => None,
                }
            },
            _ => None,
        };

        Ok(Elf64 {
            raw,
            header,
            program_table,
            section_table,
            names,
        })
    }

    pub fn class(&self) -> Class {
        self.header.identifier.class.clone()
    }

    pub fn encoding(&self) -> Encoding {
        self.header.identifier.encoding.clone()
    }

    pub fn version(&self) -> u8 {
        self.header.identifier.version
    }

    pub fn abi(&self) -> Abi {
        self.header.identifier.abi.clone()
    }

    pub fn abi_version(&self) -> u8 {
        self.header.identifier.abi_version
    }

    pub fn ty(&self) -> Type {
        self.header.ty.clone()
    }

    pub fn machine(&self) -> Machine {
        self.header.machine.clone()
    }

    pub fn format_version(&self) -> u32 {
        self.header.format_version
    }

    pub fn entry(&self) -> Address {
        self.header.entry
    }

    pub fn flags(&self) -> u32 {
        self.header.flags
    }

    pub fn program_number(&self) -> usize {
        self.program_table.length()
    }

    pub fn program(&self, index: usize) -> Result<Option<Program<'a>>, Error> {
        use core::str;

        let program_header = self.program_table.pick(index)?;
        let encoding = self.encoding();

        let start = program_header.file_offset as usize;
        let end = start + (program_header.file_size as usize);
        if self.raw.len() < end {
            return Err(Error::SliceTooShort);
        };
        let slice = &self.raw[start..end];

        let data = match program_header.ty {
            ProgramType::Null => None,
            ProgramType::Load => Some(ProgramData::Load {
                data: slice,
                address: program_header.virtual_address,
            }),
            // TODO:
            ProgramType::Dynamic => None,
            ProgramType::Interpreter => {
                let path = str::from_utf8(slice).map_err(Error::Utf8Error)?;
                Some(ProgramData::Interpreter(path))
            },
            ProgramType::Note => Some(ProgramData::Note(NoteTable::new(slice, encoding))),
            ProgramType::Shlib => None,
            ProgramType::ProgramHeaderTable => None,
            ProgramType::OsSpecific(code) => Some(ProgramData::OsSpecific {
                code,
                data: slice,
                address: program_header.virtual_address,
            }),
            ProgramType::ProcessorSprcific(code) => Some(ProgramData::ProcessorSprcific {
                code,
                data: slice,
                address: program_header.virtual_address,
            }),
            ProgramType::Unknown(code) => Some(ProgramData::Unknown {
                code,
                data: slice,
                address: program_header.virtual_address,
            }),
        };

        Ok(data.map(|d| Program {
            data: d,
            flags: program_header.flags,
            memory_size: program_header.memory_size,
            address_alignment: program_header.address_alignment,
        }))
    }

    pub fn section_number(&self) -> usize {
        self.section_table.length()
    }

    pub fn section(&self, index: usize) -> Result<Option<Section<'a>>, Error> {
        let section_header = self.section_table.pick(index)?;
        let encoding = self.encoding();

        let start = section_header.offset as usize;
        let end = start + (section_header.size as usize);
        if self.raw.len() < end {
            return Err(Error::SliceTooShort);
        };
        let slice = &self.raw[start..end];

        let data = match section_header.ty {
            SectionType::Null => None,
            SectionType::ProgramBits => Some(SectionData::ProgramBits(slice)),
            SectionType::SymbolTable => Some(SectionData::SymbolTable {
                table: Table::new(slice, encoding),
                number_of_locals: section_header.info as usize,
            }),
            SectionType::StringTable => Some(SectionData::StringTable(StringTable::new(slice))),
            SectionType::Rela => Some(SectionData::Rela {
                table: Table::new(slice, encoding),
                apply_to_section: (section_header.info as u16).into(),
            }),
            // TODO:
            SectionType::Hash => None,
            SectionType::Dynamic => None,
            SectionType::Note => Some(SectionData::Note(NoteTable::new(slice, encoding))),
            SectionType::NoBits => None,
            SectionType::Rel => Some(SectionData::Rel {
                table: Table::new(slice, encoding),
                apply_to_section: (section_header.info as u16).into(),
            }),
            SectionType::Shlib => None,
            SectionType::DynamicSymbolTable => Some(SectionData::DynamicSymbolTable {
                table: Table::new(slice, encoding),
                number_of_locals: section_header.info as usize,
            }),
            SectionType::OsSpecific(code) => Some(SectionData::OsSpecific { code, slice }),
            SectionType::ProcessorSprcific(code) => {
                Some(SectionData::ProcessorSprcific { code, slice })
            },
            SectionType::Unknown(code) => Some(SectionData::Unknown { code, slice }),
        };

        let name = match &self.names {
            Some(ref table) => table.pick(section_header.name as usize)?,
            None => "",
        };

        Ok(data.map(|d| Section {
            data: d,
            name,
            flags: section_header.flags,
            address: section_header.address,
            address_alignment: section_header.address_alignment,
            link: section_header.link,
        }))
    }
}

#[derive(Clone)]
pub enum ProgramData<'a> {
    Null,
    Load {
        data: &'a [u8],
        address: Address,
    },
    Interpreter(&'a str),
    Note(NoteTable<'a>),
    OsSpecific {
        code: u32,
        data: &'a [u8],
        address: Address,
    },
    ProcessorSprcific {
        code: u32,
        data: &'a [u8],
        address: Address,
    },
    Unknown {
        code: u32,
        data: &'a [u8],
        address: Address,
    },
}

#[derive(Clone)]
pub struct Program<'a> {
    pub data: ProgramData<'a>,
    pub flags: ProgramFlags,
    pub memory_size: u64,
    pub address_alignment: u64,
}

#[derive(Clone)]
pub enum SectionData<'a> {
    Null,
    ProgramBits(&'a [u8]),
    SymbolTable {
        table: Table<'a, SymbolEntry>,
        number_of_locals: usize,
    },
    StringTable(StringTable<'a>),
    Rela {
        table: Table<'a, RelaEntry>,
        apply_to_section: Index,
    },
    Note(NoteTable<'a>),
    Rel {
        table: Table<'a, RelEntry>,
        apply_to_section: Index,
    },
    DynamicSymbolTable {
        table: Table<'a, SymbolEntry>,
        number_of_locals: usize,
    },
    OsSpecific {
        code: u32,
        slice: &'a [u8],
    },
    ProcessorSprcific {
        code: u32,
        slice: &'a [u8],
    },
    Unknown {
        code: u32,
        slice: &'a [u8],
    },
}

#[derive(Clone)]
pub struct Section<'a> {
    pub data: SectionData<'a>,
    pub name: &'a str,
    pub flags: SectionFlags,
    pub address: Address,
    pub address_alignment: u64,
    pub link: Index,
}