Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 538
Shuzheng Avatar asked Sep 16 '25 05:09

Shuzheng


2 Answers

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 ....
like image 147
Kuba hasn't forgotten Monica Avatar answered Sep 17 '25 20:09

Kuba hasn't forgotten Monica


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.

like image 35
Peter Cordes Avatar answered Sep 17 '25 19:09

Peter Cordes