x86_64 NASM Assembly for Linux
This assembly program replaces itself with its source code. It essentially "decompiles" itself, replacing the binary.
SECTION .data source incbin __FILE__ len equ $ - source SECTION .text global _start _start: pop rdi ;number of parameters pop rdi ;path to executable, parameter of unlink and open mov rax, 87 ;unlink syscall cmp rax, 0 jl error mov rax, 2 ;open mov rsi, 0101o ;O_WRONLY O_CREAT mov rdx, 0600o ;permissions on created file syscall cmp rax, 0 jl error mov rdi, rax ;file (return value of open) mov rax, 1 ;write mov rsi, source mov rdx, len syscall cmp rax, 0 jl error mov rax, 60 ;exit mov rdi, 0 ;return code syscall error: mov rax, 60 mov rdi, 1 syscall
Compile with:
nasm -f elf64 FILENAME ld -m elf_x86_64 FILENAME.o -o FILENAME
Or the same thing in C (with inline assembly):
#include <stdio.h> extern char src; asm("src: .incbin \"" __FILE__ "\"\n.byte 0"); int main(int argc, char *argv[]) { unlink(argv[0]); FILE *file = fopen(argv[0], "w"); fprintf(file, "%s",&src); fclose(file); return 0; }
When run, the program deletes itself, and then writes its source code to the same path as the executable was at. That way, the deleted file can always be retrieved by recompiling, even if you lost the original source code.
There must be a better way to do this in C (or maybe not), but I don't know any.
Isn't that much better than just having it delete itself!
viin a single terminal environment has this effect, no escape from it unless you reboot :) Just a joke here. \$\endgroup\$echo "If you try to execute me again, it means you are an idiot.";<-- Nobody will execute more than once :P \$\endgroup\$