Search code examples
assemblynasm

What does this asm expression `64-$+buffer` means?


I'm reading NASM documentation and stuck upon the following code in section 3.2.5 TIMES: Repeating Instructions or Data

buffer: db      'hello, world' 
        times 64-$+buffer db ' '

They say this code will store exactly enough spaces to make the total length of buffer up to 64. Unfortunately, I didn't get it at all. The expression 64-$+buffer which is supposed to return a number seems very suspicious. So I want someone to explain the semantics if I didn't get right. My knowledge isn't enough to print the resulting number nor to check if the space was allocated as intended. Here is how I tried to de-parse it:

  1. 64-$+buffer is an arithmetic expression returning a number
  2. $ is a current location which should be equal to 13
  3. buffer is a labeled location and it equals to 0 if it's the very beginning of the section .data. Otherwise, we quickly get a negative number (which I suppose isn't what intended here).

If the above is true, then we get a buffer filled by 64 space characters where the first 12 is hello, world. Am I right?


Solution

  • Yes, you are right, the $ symbol is basically the current target address while assembling. Let's look at some example values:

    buffer: db 'hello, world' 
            times 64-$+buffer db ' '
    

    We'll start by setting buffer to some arbitrary address like 27. The 12 characters for the message run then from 27 thru 38 inclusive so $ will be 39 following that.

    The times count will then be (64 - 39 + 27) or 52, and that plus the 12 characters total 64.

    So yes, assuming your string is less than 64 characters, it will be padded out with enough spaces to make 64 in total (if it's longer than 64, you'll probably get an assembler error because you're supplying a negative count).