public
Last active

C is fucking crazy.

  • Download Gist
Swap.c
C
1 2 3 4 5 6 7 8 9 10 11 12
#include <stdio.h>
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);
}
 
// TIL: If you do this at work, you'll probably be fired
; ruby -e "print \"\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\"" | ndisasm -u -

00000000  8B442404          mov eax,[esp+0x4]       ; load pointers to two parameters into eax, ebx
00000004  8B5C2408          mov ebx,[esp+0x8]

00000008  8B00              mov eax,[eax]           ; load values of two parameters from pointers (*eax, *ebx) into eax, ebx
0000000A  8B1B              mov ebx,[ebx]

0000000C  31C3              xor ebx,eax             ; swap two values (eax, ebx) using xor trick
0000000E  31D8              xor eax,ebx
00000010  31C3              xor ebx,eax

00000012  8B4C2404          mov ecx,[esp+0x4]       ; load pointer to param 1 into ecx
00000016  8901              mov [ecx],eax           ; store swapped value 1 (eax) into param 1 (*ecx)

00000018  8B4C2408          mov ecx,[esp+0x8]       ; load pointer to param 2 into ecx
0000001C  8919              mov [ecx],ebx           ; store swapped value 2 (ebx) into param 2 (*ecx)

0000001E  C3                ret

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.