2

I can't get the array values printed.

The program does not display any errors until it reaches the "printloop:" label. There is some error that makes it impossible to print the values, but I cannot find it.

I hope you can.

; compile: nasm -felf64 array.asm
; linked in Ubuntu/Linux Mint: gcc -no-pie array.o -o array
; run: ./array

segment .data

lst: dq 101, 102, 103, 104, 105
len: equ (($ - lst) / 8)
fmt: dq "%lld ",10, 0

segment .text

global main

extern printf

main:
    mov ecx, len
    lea rbx, [lst]
    mov rdx, rbx      ; We'll use RDX below.
    xor edi,edi       
    xor eax,eax

pushloop:
    push qword [rbx+rdi*8]
    add rdi,1
    dec ecx
    jnz pushloop

   mov ecx, len
   xor edi, edi

poploop:
    pop rax
    mov [rdx+rdi*8], rax    
    add rdi,1
    dec ecx
    jnz poploop

    mov ecx, len
    xor edi, edi

printloop:
    mov rax, [rdx+rdi*8]
    add rdi, 1  
    mov rcx, fmt
    mov rsi, rax
    call printf wrt ..plt
    dec ecx
    jnz printloop

end:
mov     eax, 60
xor     edi,edi
syscall

Thany you in advance.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Ferran
  • 21
  • 3
  • 3
    `rax` should contain the number of SSE registers used to pass arguments to `printf`. So zero that. It's pointless to do `mov rax, [rdx+rdi*8]` followed by `mov rsi, rax` anyway. Also, you use `rdx` without initialization, that should crash before the `printloop`. Furthermore don't use direct system call to exit, instead return from `main` or `call exit`. You should also properly maintain stack alignment. Using the stack to reverse (?) an array is not optimal either. Finally, as usual, learn to use a debugger. – Jester Aug 23 '20 at 16:59
  • 1
    @Jester: RDX is initialized with `mov rdx, rbx` (for no apparent reason vs. using RBX everywhere), the problem is that the OP doesn't realize it's call-clobbered so printf steps on it. Same problem with RDI as a loop counter. – Peter Cordes Aug 23 '20 at 19:32
  • 1
    BTW, if you'd used `default rel` like you always should, this code could have worked in a PIE executable, except for the call-clobbered register bugs. IDK why you used `mov rcx, fmt` in the printf loop, though; `lea rcx, [fmt]` there would match what you did earlier for the array, and be more efficient. – Peter Cordes Aug 23 '20 at 19:39
  • I agree all the diagnosis and recomendacion. I thought I'd find a solution like "you did this wrong and I'll correct it with this" into the code. But it doesn't matter, I'll just go back to doing everything from scratch.Thank you again. – Ferran Aug 24 '20 at 06:56

0 Answers0