Grevak
Grevak

Reputation: 543

Why is the output wrong after the second call of my print function? (x86 Assembly)

I wrote a simple assembly program which is booted by the BIOS and I wrote a function which outputs the content of the register (E)SI to the screen

I have a variable called msg which is a string "Hello World1", 0xa, "Hello World2", 0xa, "Hello World3", 0xa, 0xa, 0x0

If I use the function once the output will be:

Hello World1
Hello World2
Hello World3

But if I use it twice the output will be something like that:

Hello World1
Hello World2
Hello World3

Hello World1
                          Hello World2
                          Hello World3

Why is this wrong if I use the print function twice?

My Code:


[ORG 0x7c00]

    xor     ax, ax
    mov     ds, ax
    mov     ss, ax
    mov     sp, 0x9c00
    mov     ax, 0xb800
    mov     gs, ax

    call    clear

    mov     si, msg
    mov     ah, 4
    call    print

    mov     si, msg
    mov     ah, 4
    call    print

    cli
    jmp     $

print:
    mov     bx, [vaddr]

write:
    lodsb
    cmp     al, 0
    je      end_write
    cmp     al, 0xa
    je      new_line
    mov     [gs:bx], ax
    add     bx, 2
    jmp     write

new_line:
    mov     cx, [vline]
    add     cx, 160
    mov     [vline], cx
    sub     cx, bx
    add     bx, cx

    jmp write

end_write:
    mov     [vaddr], bx
    ret

clear:
    mov     ah, 0
    mov     al, ' '
    xor     bx, bx

    mov     cx, 2000

clear_char:
    mov     [gs:bx], ax
    add     bx, 2
    loop    clear_char

    mov     byte [vaddr], 0
    mov     byte [vline], 0
    ret

msg:        db      "Hello World1", 0xa, "Hello World2", 0xa, "Hello World3", 0xa, 0xa, 0x0
vaddr:      db      0x0
vline:      dd      0

    times 510-($-$$) db 0
    db 0x55
    db 0xAA

Thanks for any help

Upvotes: 2

Views: 49

Answers (1)

Fifoernik
Fifoernik

Reputation: 9899

The definition of these variables:

vaddr:      db      0x0             BYTE
vline:      dd      0               DWORD

The setup of these variables:

mov     byte [vaddr], 0             BYTE
mov     byte [vline], 0             BYTE

The use of these variables:

mov     bx, [vaddr]                 WORD
mov     cx, [vline]                 WORD 

Simply make sure to use WORD everywhere!

Upvotes: 4

Related Questions