Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the alignment for the .data section?

I defined the following variables in the .data section in NASM:

section .data
    var1       DD   12345    ; int (4 bytes)

    var2       DB   'A'      ; char (1 byte)

    padding1   DB   123      ; 1 byte padding
    padding2   DB   123      ; 1 byte padding
    padding3   DB   123      ; 1 byte padding       

    var3       DQ   174.13   ; double (8 bytes)

In order for these variables to be correctly aligned, the .data section must be aligned to 8 bytes.

I believe that the alignment for the .data section is specified by the linker. I am using the Visual C++ 2010 linker, how can I set the alignment for the .data section using this linker?

like image 204
user8426277 Avatar asked Aug 25 '17 04:08

user8426277


1 Answers

The align directive works for data as well as code.

In the assembler's output file (an object file in the format the MSVC's linker can understand), it signals the required alignment of each section using metadata.

For example, if you use

section .data
align 1024*1024*2
foo: dd 1234
align 8       ; will assemble to 4 bytes of padding to reach the next multiple of 8
bar: dd 4567

The object file will have its required-alignment for that section set to 2MiB. For win32 object files, NASM even has special syntax for section alignment:
section .data data align=4

ELF object files (Linux) work the same way, with each section having a required-alignment.

Your object file (hopefully) doesn't end up filled with up-to-2MiB of padding, bu it might after linking if it links after something else that has a few bytes in a section that goes into the same segment as .data in the executable.

But still, knowing (or setting) the minimum alignment of the start of a section, the assembler can support align directives of any power of 2 at any point in the middle of any section. The align directive doesn't have to be at the start of a section.

like image 68
Peter Cordes Avatar answered Oct 06 '22 00:10

Peter Cordes