Jenna
Jenna

Reputation: 97

x86 Assembly; overwriting .bss values?

I'm currently trying to write a small program in ASM, and I have the following issue. I take input from the user as a string which I store in a variable I've declared in the .bss section of my code; I then re-prompt and overwrite the previously stored answer and do this multiple times. My issue is if someone has entered an answer that was shorter than the last (i.e. "James" then "Jim") I get the following output:

"Hi, James" "What's your name?" "Jim" "Hi, Jimes"

What's happening here is the characters that weren't overwritten remain and get printed, as expected. What I'm wondering is how I may go about wiping the data in the .bss db between prompts?

Here is the code so far:

section .data
 question: db "What's your name?", 10
 answer: db "Hello, "
 ln db 10



section .bss
 name resb 16

section .text
global start
start:
    call prompt
    call getName
    mov rsi, answer
    mov rdx, 7
    call print
    mov rsi, name
    mov rdx, 10
    call print
    mov rsi, ln
    mov rdx, 1
    call print
    call loop_name

    mov rax, 0x02000001
    mov rdi, 0
    syscall

reset_name:

loop_name:
    mov cx, 3
    startloop:
        cmp cx, 0
        jz endofloop
        push cx
    loopy:
        call getName
        mov rsi, answer
        mov rdx, 7
        call print
        mov rsi, name
        mov rdx, 10
        call print

        pop cx
        dec cx
        jmp startloop
    endofloop:
   ; Loop ended
   ; Do what ever you have to do here
        ret

prompt:
    mov rax, 0x02000004
    mov rdi, 1
    mov rsi, question
    mov rdx, 18
    syscall

print:
    mov rax, 0x02000004
    mov rdi, 1
    syscall
    ret

getName:
    mov rax, 0x02000003 ; read
    mov rdi, 0
    mov rsi, name
    mov rdx, 37
    syscall
 ret

Any ideas? (Variable in question is name)

Upvotes: 1

Views: 692

Answers (1)

Erik Eidt
Erik Eidt

Reputation: 26646

While I don't know the system calls you're using, we can do one of three things:

  • clear the entire variable before reusing it.
  • use and share an explicit length value to indicate how many bytes of it are valid
  • null terminate the string right after it is input

Using an explicit length value may involve someone placing a null terminator at the right point in time (e.g. just before printing).

The read operation should return to you a length that you can pass to someone else (e.g. as a pair pointer & length), or otherwise use immediately to null terminate the string.  If it doesn't, then use the first approach of clearing the entire variable before reusing it.

Typically, syscalls have return values, that indicate length on success or else negative values for failure.  In such case, you are ignoring both.

Upvotes: 2

Related Questions