Author Topic: How can save the ecx before the call ?  (Read 292 times)

seasea

  • Regular Member
  • *
  • Posts: 15
How can save the ecx before the call ?
« 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...

jj2007

  • Member
  • *****
  • Posts: 8428
  • Assembler is fun ;-)
    • MasmBasic
Re: How can save the ecx before the call ?
« Reply #1 on: April 26, 2018, 01:08:41 AM »
Try pushing two registers, in order to keep the align 16.

Vortex

  • Member
  • *****
  • Posts: 1795
Re: How can save the ecx before the call ?
« Reply #2 on: April 26, 2018, 02:25:15 AM »
Hi seasea,

Here is a quick example for you:

Code: [Select]
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

hutch--

  • Administrator
  • Member
  • ******
  • Posts: 5421
  • Mnemonic Driven API Grinder
    • The MASM32 SDK
Re: How can save the ecx before the call ?
« Reply #3 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.
hutch at movsd dot com
http://www.masm32.com    :biggrin:  :biggrin:

Mikl__

  • Member
  • ****
  • Posts: 612
Re: How can save the ecx before the call ?
« Reply #4 on: April 26, 2018, 04:32:48 PM »
Hi, seasea
it is the easy
Code: [Select]
    push rcx
    push rcx
    invoke funcitonXXX
    pop rcx
    pop rcx

jj2007

  • Member
  • *****
  • Posts: 8428
  • Assembler is fun ;-)
    • MasmBasic
Re: How can save the ecx before the call ?
« Reply #5 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.

Mikl__

  • Member
  • ****
  • Posts: 612
Re: How can save the ecx before the call ?
« Reply #6 on: April 26, 2018, 10:24:20 PM »
Ciao, jj!
scusami, ma in qualche modo non ho notato la tua risposta ...
« Last Edit: April 27, 2018, 12:53:59 AM by Mikl__ »

seasea

  • Regular Member
  • *
  • Posts: 15
Re: How can save the ecx before the call ?
« Reply #7 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: