Working with ELF files
c, elf, linux
Solution
This is way easier than you think. ELF has nothing to do with your problem (and `mmap()` is even farther...). `hello.o` is not an ELF file, it's an object file.
You can just link the object file to your executable, then you will be able to access `Hello()`. Supposing you have compiled your program to an object file as `yourCode.o`, you link this `yourCode.o` with `hello.o`
cc yourCode.o hello.o -o yourExecutable
See here.
EDIT:
If you don't want to link the file but load it dynamically, then
- `mmap()` the object file
- Get `Hello()` address in memory. You can statically analyze `hello.o` for this (e.g. using `objdump`) and get `Hello()` entry point offset in the file.
- Add this offset to the address returned by `mmap()` to get `Hello()` address.
- Map `Hello()` address to a function pointer
- Call the function.
- ???
- Profit
Problem
I need to work with simple ELF files in my C program. I can't use any external libraries, but I can use `elf.h`. Let's take hello.o file for source: ``` int Hello() { return 3; } ``` How could I access to `Hello` in ohter C program having only `hello.o` file? I should probably load it to memory using `mmap` or sth like this. At the end I need to work with much complicated ELF files, but I don't know now, how to start. UPDATE: I need to do this the way I described it, because it is for learning purposes. Whole problem is more complex that what I described. For this question assume I need to write method: ``` int HelloFromElfO(const char* helloFile); ``` which would execute `Hello` function implemented in `helloFile`. I don't want full answer. I don't need any code. I need something to start with. I have basic knowledge about ELF file structure, but I have no idea how to work in C with binary file without any parser or sth like this. UPDATE2: OK, apps like readelf are very complicated. So maybe I try this way: lets say again I have `hello.o` mapped to memory at `ptr`. How can I get pointer to `Hello` function? How can I get any structured data from `hello.o`? I mean, not pure bytes but something I can work with.