Custom prolog and epilog for a function in C++

Traditionally, the compiler is responsible for creating the prolog and epilog of a function. However, custom prolog and epilog code can be written if a function has been declared with the naked attribute.

The snippet below demonstrates a naked function with custom prolog and epilog code.

__declspec(naked) void foo(){

	// Prolog
	__asm {
		push ebp		// Push the Extended Base Pointer
		mov ebp, esp		// Set frame pointer
		sub esp, __LOCAL_SIZE	// Reserve space for local variables
		pushad			// Push all general-purpose registers
	}

	// Do stuff

	// Epilog
	__asm {
		popad			// Pop all general-purpose registers
		mov esp, ebp		// Restore stack pointer
		pop ebp			// Restore the Extended Base Pointer
		retn			// Return
	}

}

The __LOCAL_SIZE symbol can be used to let the compiler determine the amount of space needed for variables.

This entry was posted in Assembler, C++ and tagged , , , , , , , , , , , , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?