其他分享
首页 > 其他分享> > ASM - win64 -abc

ASM - win64 -abc

作者:互联网

nasm -f win64 fact.asm
default rel
bits 64

segment .text

global factorial


    ; Define constants to refer to the function arguments as offsets from RSP/RBP
    a equ    0

factorial:
    push    rbp                 ; Set up a stack frame for the function
    mov    rbp, rsp             ; Continuing the linked list here, by pointing rbp to this stack frame
    sub    rsp, 32              ; Must align on 16 byte boundary

    n equ 16                    ; Refers to current accumulated value

    ; Save local variables onto the stack frame
    mov    [rsp + a], rcx       ; save parameter a (rcx)

    cmp    rcx, 1
    jg    if_greater            ; If n <= 1, return 1
    mov    eax, 1

    leave
    ret

if_greater:
    mov    [rsp + n], rcx          ; Save current accumulated value
    dec    rcx                     ; call factorial(n-1)
    call    factorial
    mov    rcx, [rsp + n]       ; Restore original accumulated value
    imul    rax, rcx            ; Multiply factoral(n -1) * n

    leave                       ; Undo the stack frame (it sets rsp to rbp, then pops rbp.)
    ret                         ; return to calling procedure (main).


cl /EHsc main.cpp fact.obj /link  /out:cppCallAsm.exe
#include <iostream>

extern "C" int factorial(int);

using namespace std;

int main(){
    cout<< factorial(3) <<endl;
    return 0;
}

标签:abc,rcx,int,win64,frame,factorial,rsp,stack,ASM
来源: https://www.cnblogs.com/Searchor/p/16290279.html