11

I notice that there's some directives used with the .align prefix followed by numerical values.

I'm not sure on what this is, nor if it's even necessary to use, but I've wrote x86 Assembly and never used ".align" before.

What is the basic purpose of it, and why or why not is it mandatory?

Breakthrough
  • 2,444
  • 2
  • 23
  • 37
  • 2
    stackoverflow SE is where primarily programming questions are handled. The attitude expressed in your comment is neither helpful nor appreciated. – mdpc Jun 25 '13 at 19:26
  • @Waluigi Specifically, [SU] tries to focus on the *use* of consumer computer hardware and software, while [SO] focuses on the *creation* of software. The subject of assembly is generally considered to be primarily under the purview of programming ("creation" of software), and not the use of software. – Darth Android Jun 25 '13 at 19:32
  • What it actually technically does is really simple to describe: assembles padding bytes into the output file until the current position is a multiple of the given alignment. – Peter Cordes Nov 14 '16 at 00:27

1 Answers1

18

From the MSDN entry for the ALIGN directive (using MASM):

ALIGN [[number]]
Aligns the next variable or instruction on a byte that is a multiple of number.

This is often used to optimize struct placement in memory, since all new x86 architectures have a word length over 8 bits (usually 32 or 64 bits). This means that in a single memory location, you can store 4 or 8 bytes of data.

If you were to use 4 or 8 as your alignment byte size, it would ensure that the next byte to be assembled will be placed at a byte location of multiple 4 or 8, corresponding to the machine word length in this example (other alignment values are often useful depending on your application).


For example, assembling the following file (made-up syntax):

org $0x00
db  $0x01
db  $0x02
.align 4
db  $0x03

It would ensure that the 0x03 is placed on an address that is any integer multiple of 4 (includes zero!). The assembler would spit out the following bytes starting from $0x00:

Address | Data
---------------
 0x00   |  01
 0x01   |  02
 0x02   | XX/00
 0x03   | XX/00
 0x04   |  03
 ....   | ....
Breakthrough
  • 2,444
  • 2
  • 23
  • 37
  • 1
    in the case of aligning code in the midst of other code, for a jump target, I’m assuming that an assembler will spit out NOPs. Is that correct ? If so, is it a very long single NOP if it can ? What’s the time cost of very long-winded nops in this situation, since you can’t pull in as much real code as you’re having to waste time pulling in the long NOP but then you get some benefit from an aligned jump target every time round the loop? On recent CPUs is there even any point aligning loops or aligning other jump targets (for forward jumps say) ? If so, is 16 byte alignment the right value? – Cecil Ward Jul 19 '20 at 07:29