xhost + # Workaround for: QXcbConnection: Could not connect to display :0
[appimagekit.git] / getsection.c
blob35dd81acb272acdbba0cec384fbb295eb4273c55
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <sys/mman.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include "light_elf.h"
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)
12 uint8_t *data;
13 int i;
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
20 Elf32_Ehdr *elf;
21 Elf32_Shdr *shdr;
22 elf = (Elf32_Ehdr *) data;
23 shdr = (Elf32_Shdr *) (data + elf->e_shoff);
24 #elif __SIZEOF_POINTER__ == 8
25 Elf64_Ehdr *elf;
26 Elf64_Shdr *shdr;
27 elf = (Elf64_Ehdr *) data;
28 shdr = (Elf64_Shdr *) (data + elf->e_shoff);
29 #else
30 #error Platforms other than 32-bit/64-bit are currently not supported!
31 #endif
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;
40 close(fd);
41 return(0);
44 void print_hex(char* fname, unsigned long offset, unsigned long length){
45 uint8_t *data;
46 unsigned long k;
47 int fd = open(fname, O_RDONLY);
48 data = mmap(NULL, lseek(fd, 0, SEEK_END), PROT_READ, MAP_SHARED, fd, 0);
49 close(fd);
50 for (k = offset; k < offset + length; k++) {
51 printf("%x", data[k]);
53 printf("\n");
56 void print_binary(char* fname, unsigned long offset, unsigned long length){
57 uint8_t *data;
58 unsigned long k;
59 int fd = open(fname, O_RDONLY);
60 data = mmap(NULL, lseek(fd, 0, SEEK_END), PROT_READ, MAP_SHARED, fd, 0);
61 close(fd);
62 for (k = offset; k < offset + length; k++) {
63 printf("%c", data[k]);
65 printf("\n");
69 int main(int ac, char **av)
71 unsigned long offset = 0;
72 unsigned long length = 0; // Where the function will store the result
73 char* segment_name;
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);
88 return res;