Reputation:
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
Upvotes: 4
Views: 2525
Reputation: 26766
$
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.
Upvotes: 3