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

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*
   Copyright 2021 Serge Lamikhov-Center

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#![warn(missing_docs)]

//! 'elfio' is a Rust library intended for reading and generation
//! files in the ELF binary format. The library supports processing
//! of ELF files for 32- and 64-bit architectures regardless of their
//! endianess
//!
//! For example:
//! ```
//! use std::fs::File;
//! use std::io;
//! use std::io::BufReader;
//!
//! use elfio::Elfio;
//!
//! fn main() -> io::Result<()> {
//!     let elf_file = File::open("tests/files/hello_64")?;
//!     let mut file_reader = BufReader::new(elf_file);
//!
//!     let mut elf = elfio::Elfio::new();
//!
//!     elf.load(&mut file_reader)?;
//!
//!     match elf.get_type() {
//!         elfio::constant::ET_REL => println!("Object ELF file"),
//!         elfio::constant::ET_EXEC => println!("Executable ELF file"),
//!         elfio::constant::ET_DYN => println!("Shared library ELF file"),
//!         elfio::constant::ET_CORE => println!("Core ELF file"),
//!         _ => println!("ELF type is not recognized"),
//!     }
//!
//!     Ok(())
//! }
//! ```

#[macro_use]
mod macros;

mod array;
mod dynamic;
mod header;
mod modinfo;
mod note;
mod relocation;
mod section;
mod segment;
mod strings;
mod symbols;
mod types;
mod utils;

pub use array::*;
pub use dynamic::*;
use header::*;
pub use modinfo::*;
pub use note::*;
pub use relocation::*;
pub use section::ElfSectionAccessTrait;
use section::*;
pub use segment::ElfSegmentAccessTrait;
use segment::*;
use std::io;
pub use strings::*;
pub use symbols::*;
pub use types::*;
pub use utils::ElfioReadSeek;

/// Elfio - the main struct of the library. All access to ELF files attributes
/// starts from this object.
/// The object provides functions to access ELF file header attributes as well
/// as the list of segments and sections of this file.

// --------------------------------------------------------------------------
pub struct Elfio {
    header:    Box<dyn ElfHeaderTrait>,
    converter: utils::Converter,
    sections:  Vec<Box<dyn ElfSectionTrait>>,
    segments:  Vec<Box<dyn ElfSegmentTrait>>,
}

// --------------------------------------------------------------------------
impl Elfio {
    /// Create a new instance
    pub fn new() -> Self {
        Elfio {
            converter: utils::Converter { is_needed: false },
            header:    Box::new(ElfHeader::<Elf64Addr, Elf64Off>::new()),
            sections:  Vec::new(),
            segments:  Vec::new(),
        }
    }

    /// Create a new instance with defined encoding and endianess
    pub fn new_(encoding: u8, endianess: u8) -> Self {
        Elfio {
            converter: if (endianess == constant::ELFDATA2LSB && cfg!(target_endian = "little"))
                || endianess == constant::ELFDATA2MSB && cfg!(target_endian = "big")
            {
                utils::Converter { is_needed: false }
            } else {
                utils::Converter { is_needed: true }
            },
            header:    if encoding == constant::ELFCLASS64 {
                Box::new(ElfHeader::<Elf64Addr, Elf64Off>::new())
            } else {
                Box::new(ElfHeader::<Elf32Addr, Elf32Off>::new())
            },
            sections:  Vec::new(),
            segments:  Vec::new(),
        }
    }

    /// Returns a reference for an endianess converter used for the current file
    pub fn get_converter(&self) -> &utils::Converter {
        &self.converter
    }

    /// Load the ELF file from input stream
    pub fn load(&mut self, reader: &mut (dyn ElfioReadSeek)) -> io::Result<()> {
        let mut e_ident: [u8; constant::EI_NIDENT] = [0; constant::EI_NIDENT];
        // Read ELF file signature
        reader.read_exact(&mut e_ident)?;
        reader.seek(io::SeekFrom::Start(0))?;

        // Is it ELF file?
        if e_ident[constant::EI_MAG0] != constant::ELFMAG0
            || e_ident[constant::EI_MAG1] != constant::ELFMAG1
            || e_ident[constant::EI_MAG2] != constant::ELFMAG2
            || e_ident[constant::EI_MAG3] != constant::ELFMAG3
        {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "File signature doesn't conform ELF file",
            ));
        }

        if e_ident[constant::EI_CLASS] != constant::ELFCLASS64
            && e_ident[constant::EI_CLASS] != constant::ELFCLASS32
        {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Unknown ELF class value",
            ));
        }

        if e_ident[constant::EI_DATA] != constant::ELFDATA2LSB
            && e_ident[constant::EI_DATA] != constant::ELFDATA2MSB
        {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Unknown ELF file endianess",
            ));
        }

        if e_ident[constant::EI_CLASS] == constant::ELFCLASS64 {
            self.header = Box::new(ElfHeader::<Elf64Addr, Elf64Off>::new());
        } else {
            self.header = Box::new(ElfHeader::<Elf32Addr, Elf32Off>::new());
        }

        if (cfg!(target_endian = "little") && (e_ident[constant::EI_DATA] == constant::ELFDATA2LSB))
            || (cfg!(target_endian = "big")
                && (e_ident[constant::EI_DATA] == constant::ELFDATA2MSB))
        {
            self.converter.is_needed = false;
        } else {
            self.converter.is_needed = true;
        }
        self.header.set_converter(&self.converter);

        match self.header.load(reader) {
            Ok(_) => (),
            Err(e) => return Err(e),
        };

        self.load_sections(reader)?;
        self.load_segments(reader)?;

        Ok(())
    }

    /// Retrieve all ELF file sections
    pub fn get_sections(&self) -> &Vec<Box<dyn ElfSectionTrait>> {
        &self.sections
    }

    /// Retrieve all ELF file segments
    pub fn get_segments(&self) -> &Vec<Box<dyn ElfSegmentTrait>> {
        &self.segments
    }

    /// Retrieve ELF file section by its name
    pub fn get_section_by_name(&self, section_name: &str) -> Option<&dyn ElfSectionTrait> {
        for section in &self.sections {
            if section.get_name() == section_name {
                return Some(&**section);
            }
        }

        None
    }

    /// Retrieve ELF file section by its index
    pub fn get_section_by_index(&self, index: ElfHalf) -> Option<&dyn ElfSectionTrait> {
        let index = index as usize;
        if index < self.sections.len() {
            return Some(&*self.sections[index]);
        }

        None
    }

    fn load_sections(&mut self, reader: &mut (dyn ElfioReadSeek)) -> io::Result<()> {
        let entry_size = self.header.get_section_entry_size() as Elf64Off;
        let num = self.header.get_sections_num() as Elf64Off;
        let offset = self.header.get_sections_offset();

        for i in 0..num {
            let mut section = self.create_section();
            reader.seek(io::SeekFrom::Start(i * entry_size + offset))?;
            section.load(reader)?;
            self.sections.push(section);
        }

        let shstrndx = self.get_section_name_str_index();
        if shstrndx != constant::SHN_UNDEF {
            for i in 1..num {
                let pos = self.sections[i as usize].get_name_string_offset();
                let acc = StringSectionAccessor::new(self, &*self.sections[shstrndx as usize]);
                let name = acc.get_string(pos);
                self.sections[i as usize].set_name(&name);
            }
        }

        Ok(())
    }

    fn create_section(&self) -> Box<dyn ElfSectionTrait> {
        let section: Box<dyn ElfSectionTrait> = if self.header.get_class() == constant::ELFCLASS64 {
            Box::new(ElfSection::<Elf64Addr, Elf64Off, ElfXword>::new(
                &self.converter,
            ))
        } else {
            Box::new(ElfSection::<Elf32Addr, Elf32Off, ElfWord>::new(
                &self.converter,
            ))
        };

        section
    }

    fn load_segments(&mut self, reader: &mut (dyn ElfioReadSeek)) -> io::Result<()> {
        let entry_size = self.header.get_segment_entry_size() as Elf64Off;
        let num = self.header.get_segments_num() as Elf64Off;
        let offset = self.header.get_segments_offset();

        for i in 0..num {
            let mut segment = self.create_segment();
            reader.seek(io::SeekFrom::Start(i * entry_size + offset))?;
            segment.load(reader)?;
            self.segments.push(segment);
        }

        Ok(())
    }

    fn create_segment(&self) -> Box<dyn ElfSegmentTrait> {
        let segment: Box<dyn ElfSegmentTrait> = if self.header.get_class() == constant::ELFCLASS64 {
            Box::new(ElfSegment::<Elf64Addr, Elf64Off, ElfXword>::new(
                &self.converter,
                self.header.get_class(),
            ))
        } else {
            Box::new(ElfSegment::<Elf32Addr, Elf32Off, ElfWord>::new(
                &self.converter,
                self.header.get_class(),
            ))
        };

        segment
    }

    ELFIO_HEADER_ACCESS_GET!(u8, class);
    ELFIO_HEADER_ACCESS_GET!(u8, elf_version);
    ELFIO_HEADER_ACCESS_GET!(u8, encoding);
    ELFIO_HEADER_ACCESS_GET!(ElfHalf, header_size);
    ELFIO_HEADER_ACCESS_GET!(ElfHalf, section_entry_size);
    ELFIO_HEADER_ACCESS_GET!(ElfHalf, segment_entry_size);

    ELFIO_HEADER_ACCESS_GET_SET!(ElfWord, version);
    ELFIO_HEADER_ACCESS_GET_SET!(u8, os_abi);
    ELFIO_HEADER_ACCESS_GET_SET!(u8, abi_version);
    ELFIO_HEADER_ACCESS_GET_SET!(ElfHalf, type);
    ELFIO_HEADER_ACCESS_GET_SET!(ElfHalf, machine);
    ELFIO_HEADER_ACCESS_GET_SET!(ElfWord, flags);
    ELFIO_HEADER_ACCESS_GET_SET!(Elf64Addr, entry);
    ELFIO_HEADER_ACCESS_GET_SET!(ElfHalf, sections_num);
    ELFIO_HEADER_ACCESS_GET_SET!(Elf64Off, sections_offset);
    ELFIO_HEADER_ACCESS_GET_SET!(ElfHalf, segments_num);
    ELFIO_HEADER_ACCESS_GET_SET!(Elf64Off, segments_offset);
    ELFIO_HEADER_ACCESS_GET_SET!(ElfHalf, section_name_str_index);
}

impl std::fmt::Debug for Elfio {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Elfio")
            //  .field("x", &self.x)
            //  .field("y", &self.y)
            .finish()
    }
}

impl Default for Elfio {
    fn default() -> Self {
        Self::new()
    }
}