https://blog.csdn.net/Pedroa/article/details/53842115
fun.c
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
int main()
{
int fd;
int ret;
unsigned char *buf;
struct stat stat;
void *res;
unsigned long int ImageBase ;
int rebase[2] = {0x0B, 0x12};
unsigned char *temp;
ImageBase = 0x50000000;
fd = open("hello.bin", O_RDWR);
if (fd < 0) {
perror("fd");
return -1;
}
ret = fstat(fd, &stat);
if (ret < 0) {
perror("fstat");
return -1;
}
buf = (unsigned char *)malloc(stat.st_size);
if (buf == NULL) {
perror("allocate");
return -1;
}
ret = read(fd, buf, stat.st_size);
if (ret < 0 || ret != stat.st_size) {
perror("read");
return -1;
}
res = mmap((void *)ImageBase, stat.st_size, PROT_EXEC|PROT_WRITE|PROT_READ, MAP_PRIVATE, fd, 0);
if (res == MAP_FAILED) {
perror("mmap");
return -1;
}
printf("%p \n", res);
for (int i = 0; i < 2; i++)
{
*(unsigned int *)((char *)res + rebase[i]) += ImageBase;
}
temp = (unsigned char *)res;
for (int i = 0; i < 0x100; i++)
printf("%02X%s", *temp++, (i+1) % 0x10 ? " ": "\n");
__asm__ volatile ("\n\t"\
"movl $1 ,%%eax\n\t"\
"jmp *%0\n\t"\
::"mem"(res):
);
}
hello.s
.section .data
output:
.asciz "Hello World 12345678\n"
length:
.int .-output
.section .text
.global _start
_start:
movl $4, %eax
movl $1, %ebx
movl $output, %ecx
movl length, %edx
int $0x80
movl $1, %eax
movl $0, %ebx
int $0x80
makefile
all:hello.bin fun
fun: fun.c
@echo 1
gcc $< -o $@
@echo 2
hello.bin:hello.o
@echo 3
@echo "dddeeee$< = $<"
ld $< -T test.ld -o hello.elf
objcopy -j .text -O binary hello.elf hello.bin
*.o:*.s
@echo "ddd33333"
as $< -o $@
@echo "ddd$< = $<"
.PHONY clean:
-rm *.o *.bin *.elf fun
test.ld
SECTIONS
{
. = 0x00000000;
.text : {
*(.text)
*(.data)
}
}
运行结果:
TEST-master/test1# ./fun
0x50000000
B8 04 00 00 00 BB 01 00 00 00 B9 24 00 00 50 8B
14 25 3A 00 00 50 CD 80 B8 01 00 00 00 BB 00 00
00 00 CD 80 48 65 6C 6C 6F 20 57 6F 72 6C 64 20
31 32 33 34 35 36 37 38 0A 00 16 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Hello World 12345678