3
votes

What is the right way to get text section of Elf file and display it's content? I've tried to do it myself but it's showing just 250 bites of data, but when I try with readelf command it shows me much more. I think I just made wrong offset to get the section. What is the right approach?

Update: I supplemented the code. Now, it gives me segmentation fault when I want to print symbol names.

1
You could use libelf to read the elf file. - Tom Karzes
No I can't, I can only use elf.h library and nothing else - danilo
It doesn't matter for Unix, but you should use "rb" mode for binary files. - Ian Abbott
"elf.h" is a header file, not a library. The accompanied library is "libelf" and needs to be linked to your program if you use any object (variable or function) of it, what you don't plan to do, apparently. It seems that you just use the type declarations of the header file. - the busybee
PLEASE don't remove the source code from the question! It renders your question useless. - the busybee

1 Answers

1
votes

I think I just made wrong offset to get the section.

Your program iterates over all sections, so at the end of the first loop, sectHdr contains the section header of the last section, which is unlikely to the .text section.

So in the second loop you print the contents of whatever section happened to be the last.

To print the .text section, you need to save its section header when you come across it.

Update:

So if I do for loop over all sections and then strcmp with every name, and when I find matching with .text I save the adress of that header.

You don't save the address of that header -- you save the contents.

What about if I want to access to Symbol table, which is not Section (has its own type: Elf32_Sym), how do I reach that table?

The symbol table does have its own section (containing a set of Elf32_Sym records). See this answer.

Update 2:

This code:

    if(strcmp(name, ".symtab") == 0) {
        //symbolTable = (Elf32_Sym*)sectHdr.sh_addr;
        symtab = (Elf32_Shdr*) &sectHdr;
    }
    if(strcmp(name, ".strtab") == 0) {
        strtab = (Elf32_Shdr *) &sectHdr;
    }

is obviously broken: you save a pointer to memory that you overwrite on each iteration of the loop. You must save a copy of .symtab and .strtab section header (just as you do for .text).

An even better solution is to mmap the entire file into memory. Then you can save pointers to various parts of it (that's what the other answer does -- the data there points to the start of mmaped region).