nasm: how to pad the beginning of the string such that it ends right at an alignment boundary

Viewed 135

I cannot figure out how to pad the beginning of the string such that it ends right at an alignment boundary:

%macro string 1
_unaligned:
; some preprocesor expression comes here
    db %1
_aligned:
%endmacro

After several hours of trying different solutions, I still don't have any. Can anybody help, please?

EDIT:

This is the real example how it should work (for 32bit code):

%define LAST 0

%macro xword 2
%strlen len %1
                ; pad - some preprocassor magic comes here
                db %1
NAME__%2        db len
LINK__%2        dd LAST ; must be aligned !!!
CODE__%2        dd code
PAR__%2
%define LAST PAR__%2
%endmacro

Usage:

xword 'TEST',test01

creates structure (for example $ = 0x0001):

0x0001  
0x0002  
0x0003  db 'T'
0x0004  db 'E'
0x0005  db 'S'
0x0006  db 'T'
0x0007  db 4
0x0008  dd 0    ; LAST (must be ALIGNED)
0x000C  dd code

There must be no more padding than necessary, as it is necessary to save as much memory as possible.

1 Answers

This should work, though it's suboptimal as it may add more padding than necessary in some cases:

%macro string 1
   %strlen numchars %1
   align 4, db 0
   times (4-numchars)&3 db 0
   db %1
   %%_aligned:   
%endmacro

Replace 4 by whatever alignment you want (and the 3 with your alignment minus 1).


Edit: Here's another version that should avoid adding more padding than necessary:

%macro string 1
   %strlen %%numchars %1
   %%loc equ ($-$$)
   times (4-(%%loc+%%numchars))&3 db 0
   db %1
   %%_aligned:   
%endmacro

This version assumes that the start of all sections in which you use this macros are aligned on at least the same power of 2 that you want to align the data on.

Related