Is it possible to make writeable variables in .text segment using DB directive in NASM?

老子叫甜甜 提交于 2019-12-23 15:38:08

问题


I've tried declaring variables in .text segment using e.g. file_handle: dd 0.

However, trying to store something in this variable like mov [file_handle], eax results in a write error.

I know, I could declare writeable variables in the .data segment, but to make the code more compact I'd like to try it as above.

Is the only possibility to use the stack for storing these value (e.g. the file handle), or could I somehow write to my variable above?


回答1:


Executable code segments are not writable by default. This is a basic security precaution. No, it's not a good idea. But if you insist, as this is a toy project anyway, go ahead.

You can make yours writable by letting the linker know to mark it so, e.g. give the following argument to the MS linker:

link /SECTION:.text,EWR ....



回答2:


You can actually arrange for the text segment of your Windows process to be mapped read+write+execute, see @Kuba's answer. This might also be possible on Linux with ELF binaries; I think ELF has similar flags for segments.

I think you could also call a Windows function (VirtualProtect) to change the mapping of your text segment to read+write+execute from inside your process.


Overall this sounds like a terrible idea, and you should definitely keep temporaries on the stack like a C compiler would, if you want to avoid having a data page.

Static storage for things you only use in part of the program is wasteful.




回答3:


No it's not possible to have writable "variable" in .text section of an assembly program.

When writing file_handle: dd 0 in the .text section and then assemblying, your label file_handle refers to an address located in the text section of your binary. However the text section is read-only.

If the text section wasn't only read-only accessible, a program could modify itself while executing.



来源:https://stackoverflow.com/questions/38879627/is-it-possible-to-make-writeable-variables-in-text-segment-using-db-directive-i

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