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".
See also How can I make GCC compile the .text section as writable in an ELF binary?
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 (outside of shellcode testing) 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…