Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How equ $ - instruction get the length of a string in nasm syntax?

Tags:

assembly

nasm

This is a simple code to print a text:

    section .data
            myString db "This is a string for test", 10
            lengthofString equ $ -myString

    section .text
            global _start
    _start:
            mov rax, 1
            mov rdi, 1
            mov rsi, myString
            mov rdx, lengthofString
            syscall

            mov rax, 60
            mov rdi, 0
            syscall

My question is how exactly this line of the code works in this simple program?

    lengthofString equ $ -myString

1 Answers

$ represents the next free location or offset that could hold a byte (here, in the data section, at runtime).

Thus the expression $ - myString produces the difference between that next location and the label.  Since that label occurs earlier, this difference is a positive value, and in fact it is the total length of the preceding db.

The equ says to define lengthofString as a compile time constant, which doesn't consuming any runtime storage.

Note that for this to work, this equ expression containing $ must appear immediately after the string.  Otherwise, if there were intervening data declarations, the count would include them as well, which would be bad.

The following would also work, without using $, but requires two labels, and the second label must appear right after the data whose length you want:

myString db "This is a string for test", 10
endOfmyString
...
lengthofString equ endOfmyString - myString

The extra label does not add to the storage of the program, and again lengthofString is computed as a compile (assembly) time constant.

like image 110
Erik Eidt Avatar answered Sep 18 '25 17:09

Erik Eidt