问题
Is it possible to allocate memory in other sections of a NASM program, besides .data
and .bss
?
Say I want to write to a location in .text
section and receive Segmentation Fault
I'm interested in ways to avoid this and access memory legally. I'm running Ubuntu Linux
回答1:
If you want to allocate memory at runtime, reserve some space on the stack with sub rsp, 4096
or something. Or run an mmap
system call or call malloc
from libc, if you linked against libc.
If you want to test shellcode / self-modifying code, or have some other reason for have a writeable .text
:
Link with ld --omagic
or gcc -Wl,--omagic
. From the ld(1) man page:
-N
--omagic
Set the text and data sections to be readable and writable. Also, do not page-align the data segment, and disable linking against shared libraries. If the output format supports Unix style magic numbers, mark the output as "OMAGIC". Note: Although a writable text section is allowed for PE-COFF targets, it does not conform to the format specification published by Microsoft.
Or probably you can use a linker script. It might also be possible to use NASM section attribute stuff to declare a custom section that has read, write, exec permission.
There's normally no reason to do any of this, just put your static storage in .data
or .bss
, and your static read-only data in .rodata
like a normal person.
Putting read/write data near code is actively bad for performance: possible pipeline nukes from the hardware that detects self-modifying-code, and it at least pollutes the iTLB with data and the dTLB with code, if you have a page that includes some of both instead of being full of one or the other.
来源:https://stackoverflow.com/questions/61816941/allocate-writable-memory-in-the-text-section