Skip to content

Commit

Permalink
elf: define segment indexing function
Browse files Browse the repository at this point in the history
Returns a pointer to the segment in the table at the specified index.
Checks that the index is within bounds and determines the correct offset
given the structural parameters of the input ELF.
  • Loading branch information
matheusmoreira committed Aug 12, 2024
1 parent 2e2304a commit 516776a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/lone/elf.h
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,8 @@ bool lone_elf_header_machine_is_reserved(lone_u16 machine);

struct lone_elf_segments lone_elf_header_read_segments(struct lone_elf_header *header);

struct lone_elf_segment *lone_elf_segment_at(struct lone_elf_segments segments, lone_u16 index);

/* ╭────────────────────────────────────────────────────────────────────────╮
│ │
│ Functions for validating an ELF header as a whole or in parts. │
Expand Down
24 changes: 24 additions & 0 deletions source/lone/elf.c
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,30 @@ lone_elf_header_read_segments(struct lone_elf_header *header)
};
}

struct lone_elf_segment *
lone_elf_segment_at(struct lone_elf_segments table, lone_u16 index)
{
uintptr_t address;
size_t offset;

if (!table.segment.size ||
!table.segment.count ||
!table.segments ||
index >= table.segment.count) { return 0; }

address = (uintptr_t) table.segments;

if (__builtin_mul_overflow(index, table.segment.size, &offset)) {
return 0;
}

if (__builtin_add_overflow(address, offset, &address)) {
return 0;
}

return (struct lone_elf_segment *) address;
}

/* ╭────────────────────────────────────────────────────────────────────────╮
│ │
│ Writers for ELF data structures. │
Expand Down

0 comments on commit 516776a

Please sign in to comment.