Skip to content

Commit

Permalink
Remove memory allocation for ELF sections
Browse files Browse the repository at this point in the history
Since the section headers of ELF are continuous, all headers can be
accessed by getting the starting address, so there is no need to
allocate memory for this.

Remove implementation of get_elf_section_headers
  • Loading branch information
LambertWSJ committed Nov 19, 2023
1 parent ff34ba2 commit 91f6f39
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 41 deletions.
31 changes: 0 additions & 31 deletions src/elf.c
Original file line number Diff line number Diff line change
Expand Up @@ -355,37 +355,6 @@ bool elf_open(elf_t *e, const char *path)
return true;
}

struct Elf32_Shdr **get_elf_section_headers(elf_t *e)
{
struct Elf32_Ehdr *elf_hdr = (struct Elf32_Ehdr *) e->hdr;
Elf32_Half shnum = elf_hdr->e_shnum;
off_t offset = elf_hdr->e_shoff;
uint8_t *buf = e->raw_data + offset;

struct Elf32_Shdr **shdrs = malloc(sizeof(struct Elf32_Shdr) * shnum);
if (!shdrs)
return NULL;

for (int i = 0; i < shnum; i++) {
struct Elf32_Shdr *shdr = (struct Elf32_Shdr *) shdrs + i;
struct Elf32_Shdr *_shdr =
(struct Elf32_Shdr *) (buf + sizeof(struct Elf32_Shdr) * i);

shdr->sh_name = _shdr->sh_name;
shdr->sh_type = _shdr->sh_type;
shdr->sh_flags = _shdr->sh_flags;
shdr->sh_addr = _shdr->sh_addr;
shdr->sh_offset = _shdr->sh_offset;
shdr->sh_size = _shdr->sh_size;
shdr->sh_link = _shdr->sh_link;
shdr->sh_info = _shdr->sh_info;
shdr->sh_addralign = _shdr->sh_addralign;
shdr->sh_entsize = _shdr->sh_entsize;
}

return shdrs;
}

struct Elf32_Ehdr *get_elf_header(elf_t *e)
{
return (struct Elf32_Ehdr *) e->hdr;
Expand Down
3 changes: 0 additions & 3 deletions src/elf.h
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,3 @@ struct Elf32_Ehdr *get_elf_header(elf_t *e);

/* get the first byte of ELF raw data */
uint8_t *get_elf_first_byte(elf_t *e);

/* get all of the ELF section headers */
struct Elf32_Shdr **get_elf_section_headers(elf_t *e);
11 changes: 4 additions & 7 deletions tools/rv_histogram.c
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,11 @@ int main(int argc, char *args[])
}

struct Elf32_Ehdr *hdr = get_elf_header(e);
struct Elf32_Shdr **shdrs = get_elf_section_headers(e);
if (!shdrs) {
fprintf(stderr, "malloc for section headers failed\n");
return 1;
}

uintptr_t *elf_first_byte = (uintptr_t *) get_elf_first_byte(e);
struct Elf32_Shdr **shdrs =
(struct Elf32_Shdr **) (elf_first_byte +
hdr->e_shoff / sizeof(uintptr_t));

rv_insn_t ir;
bool res;

Expand Down Expand Up @@ -312,7 +310,6 @@ int main(int argc, char *args[])
print_hist_stats(rv_insn_stats, N_RV_INSNS + 1);
}

free(shdrs);
elf_delete(e);

return 0;
Expand Down

0 comments on commit 91f6f39

Please sign in to comment.