• entries
72
51
• views
60519

# The Power of MSVC++ 2005

156 views

MSVC++ 2005 is a surprisingly powerful complier. I am going to talk about some of the interesting details here to share with everyone.

declspec (naked)

Whenever a function is called, compliers embed extra code to set up and restore the stack frame before returning back to the caller. It is possible to completely strip this code out, which may be required if there is no stack frame to set up yet.

This allows us to control the stack frame directly, allowing us to write the whole routine in inline assembly--without worry of the complier adding code.

Here is an example:
__declspec (naked) void foo (){   // Add whatever code that needs to get done here...   // Setup stack frame pointer. This is normally done by C++   _asm {	mov ebp, esp	push ebp   }   // Continue adding code...}

The complier will not add ANY extra code besides that of what you have added.

declspec (noreturn)

Normally, the complier will generate a warning or error if a routine is unable to return. Sometimes, we DON'T want a routine to return. Other times, we just want to surpress the warning or error.

This can be fixed with declspec (noreturn)...
declspec (noreturn) void foo () {}

The Power of Inline assembler

The inline assembler is surprisingly powerful. It supports EVERY instruction--Including Ring 0 only instructions (LGDT, for example), and labels, allowing alot of control.

One example (Thanks to OSDev.org for this solution), is self modifying code, which I was able to perform via inline assembly:
// Generate interrupt //extern "C" __declpsec (naked) inline void geninterrupt (int interruptnum) {	_asm {                  mov AL, [ESP+4]                  mov byte ptr [run+1], AL                  jmp run	run:                  int 0        }}

The machine OPCode for the INT instruction is a 2 byte instruction of the form CD imm8.

Because there is no form that supports any indirect value, I was unable to use variables nor registers. So, instead, I modified the second byte of the machine instruction directly, prior to generating the INT call.

Yey for MSVC++[attention][attention][attention][totally][wow][inlove][grin]

...[looksaround]

I'm surprised that MS still has those ugly underscores infront of declspec and asm. In GCC they aren't there and I really don't understand why MS continues to use them. Not that I'm trying to switch you to GCC, personally I think MS's compiler is a lot better.

Also "__declpsec" is spelt wrong in the last source box, thought I should mention it incase it goes into one of the tutorials.

I used GCC in the past. It is a nice complier, but I just don't like AT&T assembly syntax. It just seems confusing to me sometimes--I'm used to Intel.

Thanks for pointing out the error -- Sorry about that! It is actually not part of a tutorial -- Not yet, anyways.

## Create an account

Register a new account