Why does MS C ++ add this code to the assembly?

I have a code (built-in assembly).

void NativeLoop()
{
    int m;
    __asm
    {
        PUSH ECX
        PUSH EDX
        MOV  ECX, 100000000
NEXTLOOP:
        MOV  EDX, ECX
        AND  EDX, 0X7FFFFFFF
        MOV  DWORD PTR m, EDX
        DEC  ECX
        JNZ  NEXTLOOP
        POP  EDX
        POP  ECX
    }
}

MS C ++ Automagicaly adds these codes (marked with **) to my procedure.
Why?
how to avoid this?

  **push        ebp  
  **mov         ebp,esp 
  **push        ecx  
  push        ecx  
  push        edx  
  mov         ecx,5F5E100h 
NEXTLOOP:
  mov         edx,ecx 
  and         edx,7FFFFFFFh 
  mov         dword ptr m,edx 
  dec         ecx  
  jnz         NEXTLOOP
  pop         edx  
  pop         ecx  
  **mov         esp,ebp 
  **pop         ebp  
  **ret
+3
source share
5 answers

This is the standard function entry and exit code. It sets and rips off the stack frame. If you do not want this, you can use __declspec (naked). Remember to enable RET if you do.

However, your fragment is based on the actual stack frame, which requires the variable "m". It is addressed in [ebp-10]. Without the preamble, the ebp register will not be set correctly, and you will corrupt the caller's stack frame.

+20

.

int NativeLoop() { }

.

+5

, __declspec(naked) MSV++, , , , .

, . . http://en.wikipedia.org/wiki/X86_calling_conventions.

Sidenote: gcc , , gcc save/restore/stackframe-code, . MSVC asm , / .

See http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#ss5.3 , the gcc inline asm syntax is uglier but more efficient.

+5
source
  **push        ebp  ;save EBP register
  **mov         ebp,esp  ;Save the stackframe
  **push        ecx  ; So that the variable `m` has an address
;...
  **mov         esp,ebp ;restore the stack frame to it original address
  **pop         ebp   ;restore EBP register
  **ret ;return from function call
+4
source

If you can search for conventions in C ++, you will understand what the compiler does.

0
source

Source: https://habr.com/ru/post/1732216/


All Articles