This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
RFC: Aligning data in buffers with a macro?
- From: "Carlos O'Donell" <carlos at systemhalted dot org>
- To: GNU C Library <libc-alpha at sourceware dot org>
- Date: Sun, 1 Apr 2012 11:30:37 -0400
- Subject: RFC: Aligning data in buffers with a macro?
We don't have any reasonable macros for aligning data inside a buffer
to a given minimum alignment.
What we have is a collection of manual C trickery to achieve either
continually growing up alignment or continually growing down
alignment.
Take for example the following snippets:
resolv/nss_dns/dns-host.c
601 uintptr_t pad = -(uintptr_t) buffer % __alignof__ (struct host_data);
602 buffer += pad;
(I was shocked this one worked since I'd never seen a construct like this)
nptl/allocatestack.c
470 /* Make sure the size of the stack is enough for the guard and
471 eventually the thread descriptor. */
472 guardsize = (attr->guardsize + pagesize_m1) & ~pagesize_m1;
473 if (__builtin_expect (size < ((guardsize + __static_tls_size
474 + MINIMAL_REST_STACK + pagesize_m1)
475 & ~pagesize_m1),
476 0))
477 /* The stack is too small (or the guard too large). */
478 return EINVAL;
...
628 # elif _STACK_GROWS_UP
629 char *guard = (char *) (((uintptr_t) pd - guardsize) &
~pagesize_m1);
630 #endif
So thus far we've got:
(1) Negative modulo
* Align with round-up semantics.
pad = -(uintptr_t) address % alignment;
address += pad;
(2) Bitwise AND of the negation
* Align with round-down semantics.
address = address & ~alignment;
(3) Add and bitwise AND of the negation
* Align with round-up semantics.
address = (address + alignment) & ~alignment;
What do people think about creating some generic macros we can use for
alignment?
That way it's crystal clear what you intend with the code.
For exmaple this...
628 # elif _STACK_GROWS_UP
629 char *guard = (char *) (((uintptr_t) pd - guardsize) &
~pagesize_m1);
630 #endif
... would become:
628 # elif _STACK_GROWS_UP
629 char *guard = (char *) ALIGN_DOWN((uintptr_t) pd -
guardsize, pagesize_m1);
630 #endif
Do the kernel headers have something we can crib or use here?
Cheers,
Carlos.