gpt4 book ai didi

linux - 自修改代码总是在 Linux 上出现段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:10 25 4
gpt4 key购买 nike

我找到了一篇关于自修改代码的文章并尝试做一些例子,但我总是遇到段错误。据我所知,存在内存权限违规。代码段是 (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:

所以在 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 start of memory region to
# change its permissions (smc-enabled)
andl $0xFFFFF000, %esi # align to start of a pagesize
pushl $7 # permissions==r|w|x
pushl $4096 # page size
pushl %esi # computed start address
call mprotect

call changer # function that does smc
mov $string, %edx
label:
push string_end-string # this code will be overridden
push $buf # and never be executed!
push $string
call memcpy
changer:
mov $offset_to_write, %esi # simple copy bytes algorithm
mov $label, %edi
mov $0xb, %ecx
loop1:
lodsb
stosb
loop loop1
ret
offset_to_write: # these instructions will be
push $0 # executed eventually
call exit
end:

最佳答案

您应该在运行时更改内存访问权限。

#include <sys/mman.h>

void *addr = get_address_of_instruction_pointer();
int length = 4096; /* size of a page */

if (mprotect(addr, length, PROT_READ | PROT_WRITE | PROT_EXEC) == 0) {
/* current code page is now writable and code from it is allowed for execution */
}

关于linux - 自修改代码总是在 Linux 上出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31305518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com