/
chflg.c
68 lines (55 loc) · 1.59 KB
/
chflg.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> // ファイルデスクリプタ関連
#include <unistd.h> // わからん
#include <elf.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define Elf_Ehdr Elf64_Ehdr
#define Elf_Phdr Elf64_Phdr
// https://smallkirby.hatenablog.com/?page=1560403658
#define IS_ELF(ehdr)\
((ehdr).e_ident[EI_MAG0] == ELFMAG0 &&\
(ehdr).e_ident[EI_MAG1] == ELFMAG1 &&\
(ehdr).e_ident[EI_MAG2] == ELFMAG2 &&\
(ehdr).e_ident[EI_MAG3] == ELFMAG3)
static int chflg(char *head){
int i;
Elf_Ehdr *ehdr;
Elf_Phdr *phdr;
ehdr = (Elf_Ehdr*)head;
if(!IS_ELF(*ehdr)){
fprintf(stderr, "This is not ELF file\n");
return -1;
}
if(ehdr->e_ident[EI_CLASS] != ELFCLASS64){
fprintf(stderr, "unknown class. (%d)\n", (int)ehdr->e_ident[EI_CLASS]);
return -1;
}
if(ehdr->e_ident[EI_DATA] != ELFDATA2LSB){
fprintf(stderr, "unknown endian. (%d)\n", (int)ehdr->e_ident[EI_DATA]);
return -1;
}
for(i=0; i < ehdr->e_phnum; i++){
phdr = (Elf_Phdr*)((char*)ehdr + ehdr->e_phoff + ehdr->e_phentsize*i);
phdr->p_flags = PF_X | PF_W | PF_R;
}
return 0;
}
int main(int argc, char *argv[]){
int fd;
struct stat sb;
char *head;
fd = open(argv[1], O_RDWR);
if(fd < 0){
fprintf(stderr, "cannot open file.\n");
exit(1);
}
fstat(fd, &sb);
head = mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if(chflg(head) < 0){
fprintf(stderr, "fail to change flags.\n");
}
close(fd);
exit(0);
}