我发现了一篇关于自修改代码的文章,并试图做一些例子,但我总是得到分段错误.就像我能理解的那样,内存权限存在违规行为.代码段是(r)ead/e(x)ecute,因此写入的尝试导致此错误.有没有办法通过在运行时或之前更改内存权限来测试程序?我正在使用linux,这个例子是用GAS汇编编写的.
.extern memcpy
.section .data
string:
.asciz "whatever"
string_end:
.section .bss
.lcomm buf, string_end-string
.section .text
.globl main
main:
call changer
mov $string, %edx
label:
push string_end-string
push $buf
push $string
call memcpy
changer:
mov $offset_to_write, %esi
mov $label, %edi
mov $0xb, %ecx
loop1:
lodsb
stosb
loop loop1
ret
offset_to_write:
push 0
call exit
end:
Run Code Online (Sandbox Code Playgroud)
所以在osgx建议的修改后,这是一个工作代码.(实际上,如果你组装并链接并运行它崩溃,但如果你看着使用gdb,它确实修改了它的代码!)
.extern memcpy
.section .data
string:
.asciz "Giorgos"
string_end:
.section .bss
.lcomm buf, string_end-string
.section .text
.globl main
main:
lea (main), %esi # get the …Run Code Online (Sandbox Code Playgroud) static void swapAddr(int *numOne, int *numTwo)
{
int *tmp;
tmp = numOne;
numOne = numTwo;
numTwo = tmp;
}
int main(void)
{
int a = 15;
int b = 10;
printf("a is: %d\n", a);
printf("Address of a: %p\n", &a);
printf("b is: %d\n", b);
printf("Address of b: %p\n", &b);
swapAddr(&a, &b);
printf("\n");
printf("a is: %d\n", a);
printf("Address of a: %p\n", &a);
printf("b is: %d\n", b);
printf("Address of b: %p\n", &b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译并运行这段代码时,输出是
a is: 15
Address of a: 0x7fff57f39b98 …Run Code Online (Sandbox Code Playgroud)