The MASM Forum

64 bit assembler => 64 bit assembler. Conceptual Issues => Topic started by: seasea on April 26, 2018, 12:57:09 AM

Title: How can save the ecx before the call ?
Post by: seasea on April 26, 2018, 12:57:09 AM
Hello, I want use the loop because it will dec ecx automaticly , but ,  the push/pop ecx before the call,  crash....
for example:

mov rcx 10
LOOP_BEGIN:
    push rcx
    invoke funcitonXXX
    pop rcx
loop LOOP_BEGIN

I'm confused about the stack...
Title: Re: How can save the ecx before the call ?
Post by: jj2007 on April 26, 2018, 01:08:41 AM
Try pushing two registers, in order to keep the align 16.
Title: Re: How can save the ecx before the call ?
Post by: Vortex on April 26, 2018, 02:25:15 AM
Hi seasea,

Here is a quick example for you:

option casemap:none

EXTERN printf:PROC
EXTERN ExitProcess:proc

.data

string      db 'This is a test.',13,10,0

.code

main PROC

LOCAL dummy:QWORD
LOCAL counter:QWORD ; aligned variable

    sub     rsp,20h
    mov     rcx,10
    mov     counter,rcx

loop_begin:

    lea     rcx,string
    call    printf

    dec     counter
    jnz     loop_begin

    xor     ecx, ecx
    call    ExitProcess

main ENDP

END
Title: Re: How can save the ecx before the call ?
Post by: hutch-- on April 26, 2018, 12:21:32 PM
Answer is simple, don't use PUSH / POP in 64 bit. It can be done but you risk the problem you have. Use a LOCAL value to preserve the register.

LOCAL reg_ :QWORD

mov reg_, rcx
; do something with ECX
mov rcx, reg_

This completely avoids stack alignment issues.
Title: Re: How can save the ecx before the call ?
Post by: Mikl__ on April 26, 2018, 04:32:48 PM
Hi, seasea
it is the easy    push rcx
    push rcx
    invoke funcitonXXX
    pop rcx
    pop rcx
Title: Re: How can save the ecx before the call ?
Post by: jj2007 on April 26, 2018, 06:33:41 PM
It is that easy in general, but I wrote "try pushing" above because of the odd case where you bump into shadow space.
Title: Re: How can save the ecx before the call ?
Post by: Mikl__ on April 26, 2018, 10:24:20 PM
Ciao, jj!
scusami, ma in qualche modo non ho notato la tua risposta ... (https://wasm.in/styles/smiles_s/blush2.gif)
Title: Re: How can save the ecx before the call ?
Post by: seasea on April 26, 2018, 11:44:36 PM
Sorry, I forgot it, the stack frame is aligned to a 16 byte. :redface:

Thank you  very much, jj2007, Vortex, hutch--, and others. :t :icon14: