Search code examples
assembly64-bitnasm

Order in which instructions are printed/executed


Why the output is in diffrent order than it is declared?

Shouldnt the output be in this order?

aaaa bbbb cccc

Instead it is:

out

I assume the issue is in assigning "bbb" value to the text variable, but i dont know why is that and how to do this the correct way.

Instructions:

    section .data
text db "aaaa", 10
text2 db "cccc", 10

section .text
    global _start

_start:
    mov rax, text
    call _printstring
   
    mov rax, "bbb"
    mov [text], rax
   
mov rax, text
    call _printstring

mov rax, text2
call _printstring

    mov eax, 60
    xor edi, edi
    syscall

_printstring:
push rax
mov rbx, 0
_printstringloop:
inc rax
inc rbx
mov cl, [rax]
cmp cl, 0
jne _printstringloop

mov rax, 1
mov rdi, 1
pop rsi
mov rdx, rbx
syscall

ret

Solution

  • Shouldnt the output be in this order?

    aaaa bbbb cccc

    Not with this code.

    What happens here is that this string is printed first: "aaaa\ncccc\n"

    _printstring does not stop at the newline, it goes all the way to the zero terminator, which wasn't explicit in the strings but there is apparently some zero-fill after the data, as usual, but in general you may not want to rely on that.

    Then:

    mov rax, "bbb"
    mov [text], rax
    

    So after that, "bbb" (no newline) is printed, as observed. This also nukes the contents of text2, since it's an 8 byte store and the last 3 of those 8 bytes are the first 3 bytes of text2, and those bytes are zero so printing text2 doesn't result in any printable text (presumably a zero character is printed, but it's invisible)