Allocate writable memory in the .text section

跟風遠走 提交于 2021-02-05 08:12:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!