#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int tmp = 0;
int sub_main(void)
{
int fd = 0;
char buf[2048] = {0};
// mprotect((void*)(0x400000), 4096*2, PROT_READ|PROT_WRITE|PROT_EXEC);
/*将代码段属性改为可读写,调用mprotect*/
/*传参的顺序是arg1 => ebx, arg2=>ecx, arg3=>edx */
__asm("mov $0x7,%edx");
// mprotect "prot" arg.PROT_READ|PROT_WRITE|PROT_EXEC
__asm("mov $0x2000,%ecx");
// mprotect "size" arg
__asm("lea (%rip), %ebx"); //
__asm("and $0xfffffffffffff000, %ebx");
// get the page of RIP register belongs to. mprotect "addr" arg
__asm("mov $0x7d,%eax");
//0x7d是mprotect的syscall number
__asm("int $0x80");
#ifdef DM
__asm("movw $0xc3c9, (%rip);");
//0xc9 is opcode for "leave", 0xce is opcode for "retq". LE mode.
#endif
__asm("nop;nop;nop;nop;nop;nop;");
fd = syscall(SYS_open, "./b.c", O_RDWR);
__asm("nop;nop;nop;nop;nop;nop;");
syscall(SYS_read, fd, buf, 2048);
__asm("nop;nop;nop;nop;nop;nop;");
syscall(SYS_close, fd);
__asm("nop;nop;nop;nop;nop;nop;");
syscall(SYS_write, 1, buf, strlen(buf)+1);
__asm("nop;nop;nop;nop;nop;nop;");
asm volatile("" : : : "memory");
// memory barrier
#ifndef DM
__asm("movl $0xc9, 0x400640");
//0xc9 is opcode for "leave"
__asm("movl $0xc3, 0x400641");
//0xce is opcode for "retq"
#endif
__asm("nop;nop;nop;nop;nop;nop;");
__asm("nop;nop;nop;nop;nop;nop;");
__asm("nop;nop;nop;nop;nop;nop;");
__asm("int $3");//中断
return 0;
}
int main()
{
int res = 0;
res = sub_main();
printf("%p\n", &tmp);
printf("%x\n", tmp);
return printf("%d\n", res);
}
===============================================================================================================================
这段代码本来是想练习syscall函数,后来又试着添加了汇编,再后来又试着把text section的属性修改,然后修改text section的内容
===============================================================================================================================