9 /* Return the offset, and the length of an ELF section with a given name in a given ELF file */
10 int get_elf_section_offset_and_lenghth(char* fname
, char* section_name
, unsigned long *offset
, unsigned long *length
)
14 int fd
= open(fname
, O_RDONLY
);
15 data
= mmap(NULL
, lseek(fd
, 0, SEEK_END
), PROT_READ
, MAP_SHARED
, fd
, 0);
17 // optionally add more architectures for 32-bit builds so that it doesn't fall back to Elf64_*
18 // see e.g. https://sourceforge.net/p/predef/wiki/Architectures/ for more predefined macro names
19 #if __SIZEOF_POINTER__ == 4
22 elf
= (Elf32_Ehdr
*) data
;
23 shdr
= (Elf32_Shdr
*) (data
+ elf
->e_shoff
);
24 #elif __SIZEOF_POINTER__ == 8
27 elf
= (Elf64_Ehdr
*) data
;
28 shdr
= (Elf64_Shdr
*) (data
+ elf
->e_shoff
);
30 #error Platforms other than 32-bit/64-bit are currently not supported!
33 char *strTab
= (char *)(data
+ shdr
[elf
->e_shstrndx
].sh_offset
);
34 for(i
= 0; i
< elf
->e_shnum
; i
++) {
35 if(strcmp(&strTab
[shdr
[i
].sh_name
], section_name
) == 0) {
36 *offset
= shdr
[i
].sh_offset
;
37 *length
= shdr
[i
].sh_size
;
44 void print_hex(char* fname
, unsigned long offset
, unsigned long length
){
47 int fd
= open(fname
, O_RDONLY
);
48 data
= mmap(NULL
, lseek(fd
, 0, SEEK_END
), PROT_READ
, MAP_SHARED
, fd
, 0);
50 for (k
= offset
; k
< offset
+ length
; k
++) {
51 printf("%x", data
[k
]);
56 void print_binary(char* fname
, unsigned long offset
, unsigned long length
){
59 int fd
= open(fname
, O_RDONLY
);
60 data
= mmap(NULL
, lseek(fd
, 0, SEEK_END
), PROT_READ
, MAP_SHARED
, fd
, 0);
62 for (k
= offset
; k
< offset
+ length
; k
++) {
63 printf("%c", data
[k
]);
69 int main(int ac, char **av)
71 unsigned long offset = 0;
72 unsigned long length = 0; // Where the function will store the result
74 segment_name = ".upd_info";
75 int res = get_elf_section_offset_and_lenghth(av[1], segment_name, &offset, &length);
76 printf("segment_name: %s\n", segment_name);
77 printf("offset: %lu\n", offset);
78 printf("length: %lu\n", length);
79 print_hex(av[1], offset, length);
80 print_binary(av[1], offset, length);
81 segment_name = ".sha256_sig";
82 printf("segment_name: %s\n", segment_name);
83 res = get_elf_section_offset_and_lenghth(av[1], segment_name, &offset, &length);
84 printf("offset: %lu\n", offset);
85 printf("length: %lu\n", length);
86 print_hex(av[1], offset, length);
87 print_binary(av[1], offset, length);