Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to executing process' image on Linux

What if process B writes (with a usual write() syscall) some data into the image of process A while the latter is executing ? Won't it cause corruption of what process A is executing ?

I'm new to Linux. As far as I understand, Unix historically does not impose mandatory file locks (like Windows does). So writing is quite possible.

I've searched the Web with no result. When I ask this question my Linux-experienced co-workers, they all answer that process A has its image entirely in-memory.

Nevertheless, from what I've read, the kernel can easily swap some pages back to the image file from memory, say, when low memory conditions are stressed. So, while on disk, some pages can potentially be corrupted by another writer process; afterwards, they can be swapped back into RAM and get executed.

like image 652
egnarts-ms Avatar asked Nov 11 '11 16:11

egnarts-ms


2 Answers

Are you thinking of a process writing into some /proc/1234/mem of another process of pid_t 1234 ?

Or are you thinking of a process writing into the ELF executable of another process?

Both scenarii are very uncommon and Linux specific (other Posix don't have these), so I don't know what can happen in that case. But at least the permission machinery should protect some.

See also the ETXTBSY error.

In practice (as shown by strace -f /usr/bin/gcc hello.c -o hello) the compiler and linker are removing the executable before open-ing it for writing the executable, so most compilation never write into an old executable file:

870   stat("hello", {st_mode=S_IFREG|0755, st_size=6096, ...}) = 0
870   unlink("hello")                   = 0
870   open("hello", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0777) = 17
870   fstat(17, {st_mode=S_IFREG|0755, st_size=0, ...}) = 0

So to write into an executable file, you have to try hard. Of course, when you do that, naughty crashes can happen.

like image 115
Basile Starynkevitch Avatar answered Oct 06 '22 00:10

Basile Starynkevitch


What have you read that suggests pages may be swapped back "to the image file"?

If the system is low on memory, pages will be swapped to the swap partition on disk, which is different from the executable file. Writing to the executable file will have no effect until the next time you run the file.

If, somehow you were able to write to the exact page on the swap file (which would be difficult, because you would have to know exactly where and when the data was written to disk). If you did that you might be able to modify the object code. Are you suggesting corrupting the executable, or some clever way to change a program while it's running?

like image 31
Joseph Stine Avatar answered Oct 06 '22 01:10

Joseph Stine