NO

Author Topic: 64-bit Variadic functions  (Read 505 times)

Offline Vortex

  • Member
  • *
  • Posts: 802
    • http://www.vortex.masmcode.com
64-bit Variadic functions
« on: July 04, 2023, 09:05:34 PM »
Hello,

Here is an example of a 64-bit variadic function. It's a simple wsprintf emulator accepting only the symbol % as format specifier.

Code: [Select]
; wsp V1.6 by Vortex - simple wsprintf emulator for NULL terminated strings
; Return value : eax holds the length of the string in the buffer

.data

wsp_table   db 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
            db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
.code

OPTION PROLOGUE:NONE
OPTION EPILOGUE:NONE

wsp PROC buffer:DWORD,format:DWORD,args:VARARG

;   rcx ->  buffer
;   rdx ->  format
;   r8  ->  args

    sub     rsp,8
    mov     QWORD PTR [rsp],rsi

    mov     QWORD PTR [rsp+8+8],rcx
    mov     QWORD PTR [rsp+24+8],r8
    mov     QWORD PTR [rsp+32+8],r9

    lea     r8,[rsp+24+8]
    mov     r9,1

    sub     rcx,r9
    mov     r11,OFFSET wsp_table
    sub     rdx,r9
@@:
    add     rcx,r9

loop1:

    add     rdx,r9
    movzx   rax,BYTE PTR [rdx]
    mov     BYTE PTR [rcx],al
    cmp     BYTE PTR [r11+rax],r9b
    jne     @b
    test    rax,rax
    jnz     @f
    mov     rax,rcx
    sub     rax,QWORD PTR [rsp+8+8]
    mov     rsi,QWORD PTR [rsp]
    add     rsp,8
    db      0C3h ; ret
@@:
    mov     r10,QWORD PTR [r8]
    xor     rsi,rsi
@@:
    movzx   rax,BYTE PTR [r10+rsi]
    mov     BYTE PTR [rcx+rsi],al
    add     rsi,r9
    test    rax,rax
    jnz     @b
    lea     rcx,[rcx+rsi-1]
    add     r8,8
    jmp     loop1

wsp ENDP

OPTION PROLOGUE:PrologueDef
OPTION EPILOGUE:EpilogueDef

END
Code it... That's all...

Offline Vortex

  • Member
  • *
  • Posts: 802
    • http://www.vortex.masmcode.com
Re: 64-bit Variadic functions
« Reply #1 on: August 13, 2023, 09:28:11 PM »
Here is a classical sample specifying the number of arguments :

Code: [Select]
OPTION PROLOGUE:NONE
OPTION EPILOGUE:NONE

CalcSum PROC counter:QWORD,args:VARARG

;   mov     QWORD PTR [rsp+8],rcx
    mov     QWORD PTR [rsp+16],rdx
    mov     QWORD PTR [rsp+24],r8
    mov     QWORD PTR [rsp+32],r9

    xor     rax,rax
    lea     r10,[rsp+16]
@@:   
    add     rax,QWORD PTR [r10]
    add     r10,8
    dec     rcx
    jnz     @b 

    retn

CalcSum ENDP


OPTION PROLOGUE:PrologueDef
OPTION EPILOGUE:EpilogueDef
Code it... That's all...