NASM 反转整数数组

NASM Reverse an integer array

从概念上讲,我试图将值压入堆栈并按 "opposite" 顺序将它们弹出。实际上,我想我正在这样做,但我不确定。我传递的数组在 section .data 中定义为 array: dd 1, 2, 3, 4, 5, 6 并且大小作为 int 值传递(3 = 3 个元素)。当我 运行 应用程序时,它链接并组装但数组没有反转。

push dword array
push dword [arrayLen]
call reverse
add esp, 8

; other stuff

reverse:
    push ebp                    ; setup stack
    mov ebp,esp 
    sub esp,0x40                ; 64 bytes of local stack space 

    ; put parameters into registers
    mov ebx, [ebp+12]           ; array
    mov edx, [ebp+8]            ; len

    ; set up loop
    mov ecx, 0

    ; push all the values onto the stack
    .loopPush:
        mov eax, 4
        mul ecx
        push dword [ebx]
        add ecx, 1
        cmp ecx, edx
            jl .loopPush
    mov ecx, 0

    ; pop all the values from the stack
    .loopPop:
        mov eax, 4
        mul edx
        pop dword [ebx+edx]
        add ecx, 1
        cmp ecx, edx
            jl .loopPop

    ; print the array
    push dword [ebp+12]
    push dword [ebp+8]
    call printArray
    add esp, 8

    .end:
        mov esp,ebp             ; undo "sub esp,0x40" above 
        pop ebp
        mov eax, ebx                ; return the reversed array
        ret 

打印功能可以准确打印我提供的任何内容,所以我大约 90% 确定打印时这不是问题。提前致谢!

首先阅读 this 以获取有关 mul 指令的信息。在您更正您的 mul 指令并在您的代码中使用结果后,一切正常。我更正您的代码如下:

section .data
    array:  dd 1, 2, 3
    arrayLen: dd 3

section .text
global main

main:
    push dword array
    push dword [arrayLen]
    call reverse
    add esp, 8


reverse:
    push ebp        ; setup stack
    mov ebp, esp
    sub esp, 0x40       ; 64 bytes of local stack space

    ; put parameters into registers
    mov ebx, [ebp + 12]           ; array
    mov edi, [ebp + 8]            ; len

    ; set up loop
    mov ecx, 0

; push all the values onto the stack
.loopPush:
    mov eax, 4
    mul ecx
    push dword [ebx + eax]
    inc ecx
    cmp ecx, edi
    jl .loopPush
    mov ecx, 0

; pop all the values from the stack
.loopPop:
    mov eax, 4
    mul ecx
    pop dword [ebx + eax]
    inc ecx
    cmp ecx, edi
    jl .loopPop

; print the array
    ;push dword [ebp+12]
    ;push dword [ebp+8]
    ;call printArray
    ;add esp, 8

.end:
    mov esp,ebp ; undo "sub esp,0x40" above                                                                     
    pop ebp
    mov eax, ebx    ; return the reversed array
    ret

抱歉,我必须评论您的代码的某些部分。