RNikoopour
RNikoopour

Reputation: 533

x86-64 Arrays Inputting and Printing

I'm trying to input values into an array in x86-64 Intel assembly, but I can't quite figure it out.

I'm creating an array in segement .bss. Then I try to pass the address of the array along to another module by using r15. Inside that module I prompt the user for a number that I then insert into the array. But it doesn't work.

I'm trying to do the following

segment .bss
dataArray resq 15                                       ; Array that will be manipulated

segment .text
mov rdi, dataArray                                      ; Store memory address of array so the next module can use it.
call inputqarray                                        ; Calling inputqarray module

Inside of inputqarary I have:

mov r15, rdi                                            ; Move the memory address of the array into r15 for safe keeping

push qword 0                                            ; Make space on the stack for the value we are reading
mov rsi, rsp                                            ; Set the second argument to point to the new locaiton on the stack
mov rax, 0                                              ; No SSE input
mov rdi, oneFloat                                       ; "%f", 0
call scanf                                              ; Call C Standard Library scanf function
call getchar                                            ; Clean the input stream

pop qword [r15]

I then try to output the value entered by the use by doing

push qword 0
mov rax, 1
mov rdi, oneFloat
movsd xmm0, [dataArray]
call printf
pop rax

Unfortunately, all I get for output is 0.00000

Upvotes: 0

Views: 2784

Answers (1)

Gunner
Gunner

Reputation: 5884

Output is 0 because you are using the wrong format specifier. It should be "%lf" Next, no need to push and pop in your procedure. Since your going to pass the address of the data array to scanf, and that will be in rsi, just pass it in rsi; one less move.

You declared your array as 15 QWORDS, is that correct - 120 bytes? or did you mean resb 15?

This works and should get you on your way:

extern printf, scanf, exit
global main

section .rodata
fmtFloatIn      db  "%lf", 0
fmtFloatOut     db  `%lf\n`, 0

section .bss
dataArray       resb 15

section .text
main:
    sub     rsp, 8                          ; stack pointer 16 byte aligned

    mov     rsi, dataArray
    call    inputqarray

    movsd   xmm0, [dataArray]
    mov     rdi, fmtFloatOut
    mov     rax, 1
    call    printf

    call    exit

inputqarray:
    sub     rsp, 8                          ; stack pointer 16 byte aligned

    ; pointer to buffer is in rsi
    mov     rdi, fmtFloatIn
    mov     rax, 0
    call    scanf

    add     rsp, 8
    ret

enter image description here

Since you are passing params in rdi to the C functions, this is not on Windows.

Upvotes: 2

Related Questions