Skip to content

Instantly share code, notes, and snippets.

@edma2
Created February 18, 2013 21:18
Show Gist options
  • Save edma2/4980842 to your computer and use it in GitHub Desktop.
Save edma2/4980842 to your computer and use it in GitHub Desktop.
#include <elf.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
Elf32_Ehdr Elf_Header;
Elf32_Shdr Section_Header;
/**
* Load the ELF header.
* Returns zero on failure, or number of bytes read.
*/
size_t load_elf_header(FILE *fp);
/**
* Read Nth section header.
* Returns zero on failure, or number of bytes read.
*/
size_t load_section_header(FILE *fp, uint16_t n);
/**
* Returns a copy of section header string table.
* Returns NULL on failure
*/
char *shstrtab(FILE *fp);
void dump_shstrtab(FILE *fp);
int main(int argc, char *argv[]) {
FILE *fp;
if (argc != 2) {
fprintf(stderr, "usage: %s <path>\n", argv[0]);
return -1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("fopen");
return -1;
}
if (!load_elf_header(fp)) {
perror("load_elf_header");
fclose(fp);
return -1;
}
dump_shstrtab(fp);
return 0;
}
size_t load_elf_header(FILE *fp) {
rewind(fp); // TODO: ftell?
return fread(&Elf_Header, sizeof(Elf32_Ehdr), 1, fp);
}
size_t load_section_header(FILE *fp, uint16_t n) {
Elf32_Off offset = Elf_Header.e_shoff + n * sizeof(Elf32_Shdr);
if (fseek(fp, offset, SEEK_SET) < 0) {
return 0;
}
return fread(&Section_Header, sizeof(Elf32_Shdr), 1, fp);
}
char *shstrtab(FILE *fp) {
if (!load_section_header(fp, Elf_Header.e_shstrndx)) {
return NULL;
}
if (fseek(fp, Section_Header.sh_offset, SEEK_SET) < 0) {
return NULL;
}
char *s = malloc(Section_Header.sh_size);
if (s) {
if (!fread(s, Section_Header.sh_size, 1, fp)) {
free(s);
return NULL;
}
}
return s;
}
void dump_shstrtab(FILE *fp) {
char *strtab = shstrtab(fp);
if (!strtab) {
perror("shstrtab");
return;
}
uint16_t i;
for (i = 0; i < Elf_Header.e_shnum; i++) {
if (!load_section_header(fp, i)) {
perror("load_section_header");
free(strtab);
return;
}
char *name = strtab + Section_Header.sh_name;
printf("section %d: %s\n", i, name);
}
free(strtab);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment