0

I want to get the full contents of any sections in an ELF file,

I can get the name of the content with this code:

int fd;
int counter;
int filesize;
void *data;
char *strtab;
Elf64_Ehdr  *elf;
Elf64_Shdr  *shdr;

counter = 0;
fd = open(av[1], O_RDONLY);
if (fd == -1) {
    perror("open : ");
    return (84);
}
filesize = lseek(fd, 0, SEEK_END);
data = mmap(NULL, filesize, PROT_READ, MAP_SHARED, fd, 0);
if (data != NULL) {
    elf = (Elf64_Ehdr *)(data);
    shdr = (Elf64_Shdr *)(data + elf->e_shoff);
    strtab = (char *)(data + shdr[elf->e_shstrndx].sh_offset);
    while(counter < elf->e_shnum) {
        printf("Contents of section %s:\n", &strtab[shdr[counter].sh_name]);
        counter ++;
    }
    return (EXIT_SUCCESS);
}
perror("mmap : ");
return (EXIT_FAILURE);

I found that the shdr structure contain many pieces of information but I want the information given by the objdump -s a.out command and I can’t find the structure that gives all the information.

Can you help me to find a lead or a name of a structure where I can find this information, please?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Laodis
  • 17
  • 5
  • `void` pointer arithmetic is undefined behavior. You can fix that with `(Elf64_Shdr *)((char *)data + elf->e_shoff)` – S.S. Anne Mar 02 '20 at 19:44
  • Do you want the disassembly, or just code in binary form? – PiRocks Mar 02 '20 at 19:44
  • i want to get information in this format: `Contents of section .rodata: 0000 67452301 efcdab89 67452301 efcdab89 gE#.....gE#..... 0010 64636261 68676665 64636261 68676665 dcbahgfedcbahgfe` – Laodis Mar 02 '20 at 20:26
  • look at the code of `objdump`? The question as it stands is way to broad. – J. Doe Mar 02 '20 at 20:31

1 Answers1

1

This is a bug:

if (data != NULL) {

because mmap doesn't return NULL on failure (it returns MAP_FAILED).

Your shdr variable points to struct Elf64_Shdr, which has .sh_offset and .sh_size fields. To get the contents of the section, you want to dump .sh_size bytes located at (char *)data + shdr->sh_offset.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362