Skip to content

Commit

Permalink
Init project
Browse files Browse the repository at this point in the history
  • Loading branch information
wenxuanjun committed Nov 2, 2024
0 parents commit d56f8df
Show file tree
Hide file tree
Showing 10 changed files with 272 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[unstable]
build-std-features = ["compiler-builtins-mem"]
build-std = ["core", "compiler_builtins", "alloc"]

[build]
target = ["i686-unknown-none.json", "x86_64-unknown-none"]
53 changes: 53 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: Build and Release

permissions:
contents: write

on:
push:
branches: [ "main" ]
paths-ignore:
- 'README.md'
- '.gitignore'

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: nightly
override: true

- name: Add x86_64-unknown-none target
run: rustup target add x86_64-unknown-none

- name: Install cbindgen
run: cargo install cbindgen

- name: Add rust-src component
run: rustup component add rust-src

- name: Build general release
run: |
cargo build --release
mv target/x86_64-unknown-none/release/libelf_parse.a libelf_parse-x86_64.a
mv target/i686-unknown-none/release/libelf_parse.a libelf_parse-i686.a
- name: Generate header
run: cbindgen --output elf_parse.h

- name: Release artifacts
uses: softprops/action-gh-release@v2
with:
name: Nightly build
tag_name: release
files: |
libelf_parse-x86_64.a
libelf_parse-i686.a
elf_parse.h
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Cbindgen files
*.h

# Build cache
/target
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "libelf_parse"
edition = "2021"

[lib]
name = "elf_parse"
crate-type = ["staticlib"]

[profile.dev]
panic = "abort"

[profile.release]
panic = "abort"
lto = true
opt-level = 3
strip = true
codegen-units = 1

[dependencies.object]
version = "0.36.5"
features = ["read_core", "elf", "unaligned"]
default-features = false
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023-2024 wenxuanjun

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.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# libelf-parse

C binding of `object` crate for x86 or x86_64 OS to parse ELF files easily.

## Usage

Download the header file and lib from [releases](https://github.com/plos-clan/libelf-parse/releases/tag/release).

Link the library to your project.

## Build

Build directly to get the two target files:

```bash
cargo build --release
```

The production build will be in `target/release/<target>/` directory.

And use `cbindgen` to generate the header file:

```bash
cargo install cbindgen
cbindgen --output elf_parse.h
```
5 changes: 5 additions & 0 deletions cbindgen.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
language = "C"
pragma_once = true
no_includes = true
cpp_compat = true
usize_is_size_t = true
15 changes: 15 additions & 0 deletions i686-unknown-none.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"llvm-target": "i686-unknown-none",
"data-layout": "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i128:128-f64:32:64-f80:32-n8:16:32-S128",
"arch": "x86",
"target-endian": "little",
"target-pointer-width": "32",
"target-c-int-width": "32",
"os": "none",
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float"
}
94 changes: 94 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#![no_std]
#![no_main]
#![feature(alloc_error_handler)]

extern crate alloc;

use core::alloc::{GlobalAlloc, Layout};
use core::ffi::c_void;
use core::panic::PanicInfo;
use core::slice::from_raw_parts;
use object::{File, Object, ObjectSegment};

#[panic_handler]
unsafe fn panic(_info: &PanicInfo) -> ! {
loop {}
}

#[global_allocator]
static ALLOCATOR: Allocator = Allocator;

#[alloc_error_handler]
fn alloc_error_handler(layout: Layout) -> ! {
panic!("Allocation error: {:?}", layout);
}

struct Allocator;

static mut MALLOC: Option<extern "C" fn(usize) -> *mut c_void> = None;
static mut FREE: Option<extern "C" fn(*mut c_void)> = None;

unsafe impl GlobalAlloc for Allocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
MALLOC.unwrap()(layout.size()) as *mut u8
}

unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
FREE.unwrap()(ptr as *mut c_void);
}
}

#[repr(C)]
pub struct Segment {
address: u64,
size: u64,
data: *const u8,
}

impl Segment {
pub fn new(address: u64, size: u64, data: *const u8) -> Self {
Self { address, size, data }
}
}

#[repr(C)]
pub enum ParseElfError {
None = 0,
InvalidElfData,
FailedToGetSegmentData,
AllocFunctionNotProvided,
}

#[no_mangle]
pub unsafe extern "C" fn parse_elf(
elf_data: *const u8,
elf_size: usize,
callback: extern "C" fn(segment: Segment),
malloc: Option<extern "C" fn(usize) -> *mut c_void>,
free: Option<extern "C" fn(*mut c_void)>,
) -> ParseElfError {
if malloc.is_none() || free.is_none() {
return ParseElfError::AllocFunctionNotProvided;
}

MALLOC = malloc;
FREE = free;

let buffer = from_raw_parts(elf_data, elf_size);

let binary = match File::parse(buffer) {
Ok(file) => file,
Err(_) => return ParseElfError::InvalidElfData,
};

for segment in binary.segments() {
let data = match segment.data() {
Ok(d) => d,
Err(_) => return ParseElfError::FailedToGetSegmentData,
};

callback(Segment::new(segment.address(), segment.size(), data.as_ptr()));
}

ParseElfError::None
}

0 comments on commit d56f8df

Please sign in to comment.