Stack Example

From SkullSecurity
Revision as of 18:10, 13 March 2007 by 207.34.103.194 (talk) (New page: {{Infobox assembly}} Category: Assembly Examples I've tested this, and it should work as intended: <pre> #include <stdio.h> void __declspec(naked) swap(int *a, int *b) { __asm { ...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
Assembly Language Tutorial
Please choose a tutorial page:

I've tested this, and it should work as intended:

#include <stdio.h>

void __declspec(naked) swap(int *a, int *b)
{
	__asm
	{
		push ebp      ; Preserve ebp.
		mov ebp, esp  ; Set up the frame pointer.
		sub esp, 8    ; Make room for two local variables.
		push esi      ; Preserve esi on the stack.
		push edi      ; Preserve edi on the stack.

		mov ecx, [ebp+8]   ; Put the first parameter (a pointer) into ecx.
		mov edx, [ebp+12]  ; Put the second parameter (a pointer) into edx.

		mov esi, [ecx] ; Dereference the pointer to get the first parameter.
		mov edi, [edx] ; Dereference the pointer to get the second parameter.

		mov [ecx], edi ; Put the second value into the first address.
		mov [edx], esi ; Put the first value into the second address.
		
		pop edi        ; Restore the edi register
		pop esi        ; Restore the esi register
		add esp, 8     ; Remove the local variables from the stack
		pop ebp        ; Restore ebp
		ret            ; Return (eax isn't set, so there's no return value)
	}
}

int main(int argc, char* argv[])
{
	int a = 3; 
	int b = 4;

	printf("a = %d, b = %d\n", a, b);
	swap(&a, &b);
	printf("a = %d, b = %d\n", a, b);

	while(1)
		;

	return 0;
}