Defining a variable inside a C ++ inline assembly

Say we have the following C ++ code:

int var1;

__asm {
    mov var1, 2;
}

Now, what I would like to know, I would not want to define var1 outside the __asm ​​directive, so that I would have to do to put it in it. Is it possible?

thanks

+5
source share
3 answers

To do this, you need to create a “naked” method using _declspec (naked) and write yourself a prologue and epilogue, which are usually created by the compiler.

The purpose of the prologue is to:

  • configure EBP and ESP
  • reserve stack space for local variables
  • save registers that must be changed in the function body

The epilogue should:

  • restore saved register values

push        ebp                ; Save ebp
mov         ebp, esp           ; Set stack frame pointer
sub         esp, localbytes    ; Allocate space for locals
push        <registers>        ; Save registers

:

pop         <registers>   ; Restore registers
mov         esp, ebp      ; Restore stack pointer
pop         ebp           ; Restore ebp
ret                       ; Return from function

(ebp - 4) (ebp - 4 - localbytes). (ebp + 8) .

+12

C : C ( ), , ​​ C.

, , , extern C. , , , .

asm, . , asm,

sub esp, 12       ; space for 3 asm-local 32bit vars
mov [esp-8], 42   ; set value of local var
[...]
push 0xdeadbeaf   ; use stack
[...]             ; !!! 42 resides now in [esp-12] !!!
add esp, 16       ; restore esp

, , (.. push pop), (.. ebp locals ), cedrou.

+3

ESP, :

__asm
{
    add esp, 4
    mov [esp], 2;
    ...
    sub esp, 4
}

Typically, this is better handled by creating a "stack frame" for the calling function, and then accessing local variables (and functional parameters) using offsets inside the frame instead of directly using the ESP register, that is:

__asm
{
    push ebp
    mov ebp, esp
    add esp, 4
    ...
    mov [ebp-4], 2;
    ...
    mov esp, ebp
    pop ebp
}
+3
source

All Articles