C can be crazy
C can be crazy some times.
#include
void(*swap)() = (void(*)()) "\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3"
"Oh, there you are Mr. Insanity...";
int main(){ // works on GCC 3+4
int a = 37, b = 13;
swap(&a, &b);
printf("%d%d",a,b);
}
So, what the fuckĀ is going on?
This code, basically, takes a block of raw instructions, stick it into the memory, and gets casted into a function (void(*)()).
In Intel asm, the mnemonics would be as follows:
mov eax, [esp+4] ;\x8b\x44\x24\x04
mov ebx, [esp+8] ;\x8b\x5c\x24\x08
mov eax, ds:[eax] ;\x8b\x00
mov ebx, ds:[ebx] ;\x8b\x1b
xor eax, ebx ;\x31\xc3
xor ebx, eax ;\x31\xd8 Actual swapping done here
xor eax, ebx ;\x31\xc3
mov ecx, [esp+4] ;\x8b\x4c\x24\x04
mov ds[ecx], eax ;\x89\x01
mov ecx, [esp+8] ;\x8b\x4c\x24\x08
mov ds[ecx], ebx ;\x89\x19
ret ;\xc3