GithubHelp home page GithubHelp logo

gz / rust-elfloader Goto Github PK

View Code? Open in Web Editor NEW
111.0 5.0 23.0 247 KB

Library to load and relocate ELF files.

Home Page: https://docs.rs/elfloader

License: Apache License 2.0

Rust 99.12% C 0.88%

rust-elfloader's Introduction

Build cargo-badge docs-badge

elfloader

A library to load and relocate ELF files in memory. This library depends only on libcore so it can be used in kernel level code, for example to load user-space programs.

How-to use

Clients will have to implement the ElfLoader trait:

use elfloader::*;
use log::info;

/// A simple ExampleLoader, that implements ElfLoader
/// but does nothing but logging
struct ExampleLoader {
    vbase: u64,
}

impl ElfLoader for ExampleLoader {
    fn allocate(&mut self, load_headers: LoadableHeaders) -> Result<(), ElfLoaderErr> {
        for header in load_headers {
            info!(
                "allocate base = {:#x} size = {:#x} flags = {}",
                header.virtual_addr(),
                header.mem_size(),
                header.flags()
            );
        }
        Ok(())
    }

    fn relocate(&mut self, entry: RelocationEntry) -> Result<(), ElfLoaderErr> {
        use RelocationType::x86_64;
        use crate::arch::x86_64::RelocationTypes::*;

        let addr: *mut u64 = (self.vbase + entry.offset) as *mut u64;

        match entry.rtype {
            x86_64(R_AMD64_RELATIVE) => {

                // This type requires addend to be present
                let addend = entry
                    .addend
                    .ok_or(ElfLoaderErr::UnsupportedRelocationEntry)?;

                // This is a relative relocation, add the offset (where we put our
                // binary in the vspace) to the addend and we're done.
                info!(
                    "R_RELATIVE *{:p} = {:#x}",
                    addr,
                    self.vbase + addend
                );
                Ok(())
            }
            _ => Ok((/* not implemented */)),
        }
    }

    fn load(&mut self, flags: Flags, base: VAddr, region: &[u8]) -> Result<(), ElfLoaderErr> {
        let start = self.vbase + base;
        let end = self.vbase + base + region.len() as u64;
        info!("load region into = {:#x} -- {:#x}", start, end);
        Ok(())
    }

    fn tls(
        &mut self,
        tdata_start: VAddr,
        _tdata_length: u64,
        total_size: u64,
        _align: u64
    ) -> Result<(), ElfLoaderErr> {
        let tls_end = tdata_start +  total_size;
        info!("Initial TLS region is at = {:#x} -- {:#x}", tdata_start, tls_end);
        Ok(())
    }

}

// Then, with ElfBinary, a ELF file is loaded using `load`:
fn main() {
    use std::fs;

    let binary_blob = fs::read("test/test.x86_64").expect("Can't read binary");
    let binary = ElfBinary::new(binary_blob.as_slice()).expect("Got proper ELF file");
    let mut loader = ExampleLoader { vbase: 0x1000_0000 };
    binary.load(&mut loader).expect("Can't load the binary?");
}

rust-elfloader's People

Contributors

cole14 avatar dadoum avatar dependabot[bot] avatar gz avatar landhb avatar marek-g avatar onurcancamci avatar petrochenkov avatar toku-sa-n avatar trolldemorted avatar yrashk avatar zoxc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

rust-elfloader's Issues

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 rust-elfloader developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT/Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

Incorrect method description

rust-elfloader/src/lib.rs

Lines 193 to 194 in 238778b

/// Allocates a virtual region of `size` bytes at address `base`.
fn allocate(&mut self, load_headers: LoadableHeaders) -> Result<(), &'static str>;

Neither size nor base exist. Should the description be like: "Allocates a region specified by load_headers."?

load refuses to load non-x86_64 elfs

because of the check in is_loadable:

rust-elfloader/src/lib.rs

Lines 306 to 328 in 431cca1

fn is_loadable(&self) -> Result<(), &'static str> {
let header = self.file.header;
let typ = header.pt2.type_().as_type();
if header.pt1.class() != header::Class::SixtyFour {
Err("Not 64bit ELF")
} else if header.pt1.version() != header::Version::Current {
Err("Invalid version")
} else if header.pt1.data() != header::Data::LittleEndian {
Err("Wrong Endianness")
} else if !(header.pt1.os_abi() == header::OsAbi::SystemV
|| header.pt1.os_abi() == header::OsAbi::Linux)
{
Err("Wrong ABI")
} else if !(typ == header::Type::Executable || typ == header::Type::SharedObject) {
error!("Invalid ELF type {:?}", typ);
Err("Invalid ELF type")
} else if header.pt2.machine().as_machine() != header::Machine::X86_64 {
Err("ELF file is not for x86-64 machine")
} else {
Ok(())
}
}

Is that check necessary? I have to initialize memory regions in an arm emulator and would like to use elfloader for that (I assumed it parses arm64-elfs correctly).

Cant iterate symbol table for risc-v elf binary

Hello,

The code below gives the error .symtab does not contain a symbol table. But there is definately a symbol table in the elf binary.

let binary_blob = fs::read("../main").unwrap();
let binary = ElfBinary::new("main", binary_blob.as_slice()).unwrap();
binary
    .for_each_symbol(|e| println!("{}", e.name()))
    .unwrap();

The binary is a c code compiled for riscv32id architecture, but this rust code runs on x64 linux. I can read program headers and entry point without a problem.

Elf binary is compiled with riscv32-unknown-elf-gcc main.c -march=rv32id -o main -ffreestanding -nostdlib
readelf -a result is as follows:

ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           RISC-V
  Version:                           0x1
  Entry point address:               0x102e0
  Start of program headers:          52 (bytes into file)
  Start of section headers:          1496 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         2
  Size of section headers:           40 (bytes)
  Number of section headers:         9
  Section header string table index: 8

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .text             PROGBITS        00010074 000074 0002c8 00  AX  0   0  4
  [ 2] .rodata           PROGBITS        0001033c 00033c 00000b 00   A  0   0  4
  [ 3] .sbss             NOBITS          00011348 000348 000004 00  WA  0   0  4
  [ 4] .comment          PROGBITS        00000000 000347 000012 01  MS  0   0  1
  [ 5] .riscv.attributes LOPROC+0x3      00000000 000359 000026 00      0   0  1
  [ 6] .symtab           SYMTAB          00000000 000380 000170 10      7   8  4
  [ 7] .strtab           STRTAB          00000000 0004f0 00009c 00      0   0  1
  [ 8] .shstrtab         STRTAB          00000000 00058c 00004a 00      0   0  1
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
  L (link order), O (extra OS processing required), G (group), T (TLS),
  C (compressed), x (unknown), o (OS specific), E (exclude),
  p (processor specific)

There are no section groups in this file.

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  LOAD           0x000000 0x00010000 0x00010000 0x00347 0x00347 R E 0x1000
  LOAD           0x000348 0x00011348 0x00011348 0x00000 0x00004 RW  0x1000

 Section to Segment mapping:
  Segment Sections...
   00     .text .rodata
   01     .sbss

There is no dynamic section in this file.

There are no relocations in this file.

The decoding of unwind sections for machine type RISC-V is not currently supported.

Symbol table '.symtab' contains 23 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00010074     0 SECTION LOCAL  DEFAULT    1
     2: 0001033c     0 SECTION LOCAL  DEFAULT    2
     3: 00011348     0 SECTION LOCAL  DEFAULT    3
     4: 00000000     0 SECTION LOCAL  DEFAULT    4
     5: 00000000     0 SECTION LOCAL  DEFAULT    5
     6: 00000000     0 FILE    LOCAL  DEFAULT  ABS main.c
     7: 00010284    92 FUNC    LOCAL  DEFAULT    1 __internal_syscall
     8: 00011b47     0 NOTYPE  GLOBAL DEFAULT  ABS __global_pointer$
     9: 00011347     0 NOTYPE  GLOBAL DEFAULT    2 __SDATA_BEGIN__
    10: 00010154   152 FUNC    GLOBAL DEFAULT    1 puts
    11: 000101ec    76 FUNC    GLOBAL DEFAULT    1 malloc
    12: 000100bc    72 FUNC    GLOBAL DEFAULT    1 print_number
    13: 000102e0    92 FUNC    GLOBAL DEFAULT    1 _start
    14: 0001134c     0 NOTYPE  GLOBAL DEFAULT    3 __BSS_END__
    15: 00011347     0 NOTYPE  GLOBAL DEFAULT    3 __bss_start
    16: 00011347     0 NOTYPE  GLOBAL DEFAULT    2 __DATA_BEGIN__
    17: 00011347     0 NOTYPE  GLOBAL DEFAULT    2 _edata
    18: 0001134c     0 NOTYPE  GLOBAL DEFAULT    3 _end
    19: 00010074    72 FUNC    GLOBAL DEFAULT    1 exit
    20: 00011348     4 OBJECT  GLOBAL DEFAULT    3 a
    21: 00010104    80 FUNC    GLOBAL DEFAULT    1 put_char
    22: 00010238    76 FUNC    GLOBAL DEFAULT    1 free

No version information found in this file.

Rustc version is 1.45.0-nightly (a08c47310 2020-05-07)
elfloader version is v0.10.0

BSS and empty sections

How are bss sections loaded?
Just allocate is called or is load also called with zero values?
The reason is that zeroing of memory is not needed in case load is called.

Can you please call this out in docs / examples?

Loading TLS - Raw data

The current tls signature fn tls(&mut self, tdata_start: u64, tdata_length: u64, total_size: u64, align: u64) provides no means to access the TLS image itself. There is no access to a region in order for the loader to actually load the binary.

Please provide an array access to the TLS's tdata image

Not working ELF on the amd64 x86_64 Linux

Hi,

I use Linux Linux kali 5.10.0-kali7-amd64 #1 SMP Debian 5.10.28-1kali1 (2021-04-12) x86_64 GNU/Linux and i run your example :

use elfloader::*;
use log::info;

/// A simple ExampleLoader, that implements ElfLoader
/// but does nothing but logging
struct ExampleLoader {
    vbase: u64,
}

impl ElfLoader for ExampleLoader {
    fn allocate(&mut self, load_headers: LoadableHeaders) -> Result<(), ElfLoaderErr> {
        for header in load_headers {
            info!(
                "allocate base = {:#x} size = {:#x} flags = {}",
                header.virtual_addr(),
                header.mem_size(),
                header.flags()
            );
        }
        Ok(())
    }

    fn relocate(&mut self, entry: RelocationEntry) -> Result<(), ElfLoaderErr> {
        use RelocationType::x86_64;
        use crate::arch::x86_64::RelocationTypes::*;

        let addr: *mut u64 = (self.vbase + entry.offset) as *mut u64;
        match entry.rtype {
            x86_64(R_AMD64_RELATIVE) => {

                // This type requires addend to be present
                let addend = entry
                    .addend
                    .ok_or(ElfLoaderErr::UnsupportedRelocationEntry)?;

                // This is a relative relocation, add the offset (where we put our
                // binary in the vspace) to the addend and we're done.
                info!(
                    "R_RELATIVE *{:p} = {:#x}",
                    addr,
                    self.vbase + addend
                );
                Ok(())
            }
            _ => Ok(print!("Not work")), //Ok((/* not implemented */)),
        }
    }

    fn load(&mut self, flags: Flags, base: VAddr, region: &[u8]) -> Result<(), ElfLoaderErr> {
        let start = self.vbase + base;
        let end = self.vbase + base + region.len() as u64;
        info!("load region into = {:#x} -- {:#x}", start, end);
        Ok(())
    }

    fn tls(
        &mut self,
        tdata_start: VAddr,
        _tdata_length: u64,
        total_size: u64,
        _align: u64
    ) -> Result<(), ElfLoaderErr> {
        let tls_end = tdata_start +  total_size;
        info!("Initial TLS region is at = {:#x} -- {:#x}", tdata_start, tls_end);
        Ok(())
    }

}

// Then, with ElfBinary, a ELF file is loaded using `load`:
fn main() {
    use std::fs;

    let binary_blob = fs::read("test/test.x86_64").expect("Can't read binary");
    let binary = ElfBinary::new(binary_blob.as_slice()).expect("Got proper ELF file");
    let mut loader = ExampleLoader { vbase: 0x1000_0000 };
    binary.load(&mut loader).expect("Can't load the binary?");
   
}

I get output :

Not work 
Not work 
Not work 
Not work 
Not work 

What's the problem?

Thanks,

Loading ELF on x64 Linux

I'm having some trouble implementing an ELF loader in Linux with the ElfLoader trait. Questions:

  1. When allocating memory for each section, does the base address need to match what is in the section header?
  2. It doesn't look like this crate has a function for jumping to the start point of the loaded ELF and begin executing, how would that be done with this crate? Could I maybe open a pull request to add that functionality?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.