2
section.text:
global _start

_start:
    mov ebx, 1
    mov eax, 4
    mov ecx, msg1
    mov edx, len1
    int 0x80

    mov eax, 1 ; exit
    mov ebx, 0
    int 0x80


section.data:
msg1: db "Hello world", 10
msg2: db "Hello world!", 10
len1: equ $-msg1
len2: equ $-msg2

it prints out: Hello world Hello world! but why msg2?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

1 Answers1

5

len1 is populated incorrectly, it should be:

section  .rodata        ; space needed between section directive and its operand
                        ; On Linux we normally put read-only data in .rodata

msg1: db "Hello world", 10
len1: equ $-msg1
msg2: db "Hello world!", 10
len2: equ $-msg2

So len1 is a difference between current address ($) and the address of msg1. This way it would be a length of first message.

See How does $ work in NASM, exactly? for more details and examples.


Note that section.data: is just a label defining a symbol name with a dot in the middle. It doesn't switch sections, so your code and data are in the .text section (with read-only + exec permission), which is the default section at the top of the file for nasm -f elf32 outputs.

Use section .data if you want read+write without exec, or section .rodata on Linux if you want read-only without exec, where compilers put string literals and other constants to group them together separate from code.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Renat
  • 7,718
  • 2
  • 20
  • 34
  • 1
    We have a duplicate for that ([In NASM labels next to each other in memory are printing both strings instead of first one](https://stackoverflow.com/q/26897633)) and a canonical Q&A about `$` in general, including this problem. ([How does $ work in NASM, exactly?](https://stackoverflow.com/q/47494744)). I expect those would be hard to find if you didn't know a specific phrase to search for / autocomplete, though. The previous duplicate has a longer question for people to scroll past to get to the answer, so maybe this one's actually a better target for future dups. – Peter Cordes Jun 21 '22 at 05:49