Editing files in place

Reading the rsync(1) manpages, the option --inplace doc­u­men­ta­tion alerts of:

In-use binaries cannot be updated (either the OS will prevent this from happening, or binaries that attempt to swap-in their data will misbehave or crash).

Some time ago I tried to write a program which would modify it's own binary to save data (without a specific motivation), but it resulted in errors when modifing it's binary while in use, also, it's possible (in POSIX systems) to delete files used in that moment. The read of the option above showed a viable path to do this, so here is the program which modifies it's own binary to save a number, it does this by loading the file in memory, unlinking it and creating a new one... probably the memory address location could be done in a more sofisti­cat­ed manner, but it's only a test program.

May give a warning at compile-time, memmem doesn't get away well with volatile values, but this property is needed to make sure that structure is not optimized out.


$ gcc selfedit-unlink.c -o selfedit
selfedit-unlink.c: In function ‘locate_value’:
selfedit-unlink.c:58:5: warning: passing argument 3 of ‘memmem’ discards ‘volatile’ qualifier from pointer target type [enabled by default]
/usr/include/string.h:382:14: note: expected ‘const void *’ but argument is of type ‘volatile char *’
$ ./selfedit 
Stored: 0
$ ./selfedit 7
Stored: 0
$ ./selfedit 
Stored: 7
$ ./selfedit 11
Stored: 7
$ ./selfedit 13
Stored: 11
$ ./selfedit 
Stored: 13

Now... the problem is to find a use case for this :P