Re: [PATCH V2 2/3] MdePkg/Base.h: Introduce various alignment-related macros


Marvin Häuser <mhaeuser@...>
 

Ping? :)

On 16.08.21 15:10, Marvin Häuser wrote:
Hey Ray,

On 16/08/2021 11:42, Ni, Ray wrote:
Marvin,
So lucky to have you in the edk2 project looking into these fundamentals!
Thank you. :)

+  #define ALIGNOF(TYPE) OFFSET_OF (struct { CHAR8 C; TYPE A; }, A)

1. Does struct{} inside a macro conform to C standard? How is the compatibility with different compilers?
This should work, yes. The C standard defines offsetof as such:

"The macros are [...]

        offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of
which is the offset in bytes, to the structure member (designated by member-designator),
from the beginning of its structure (designated by type). The type and member designator
shall be such that given

        static type t;

then the expression &(t.member-designator) evaluates to an address constant. [...]" [1]

If we plug in t:

        static struct { CHAR8 C; TYPE A; } t;

we get a valid static storage duration variable declaration that satisfies the the last condition because:

"An address constant is [...], a pointer to an lvalue designating an object of static
storage duration, or [...]" [2]

It worked with all compilers I tinkered with at https://godbolt.org/
I sadly do not have access to any of the compilers where this may be used effectively (RVCT, EBC).

+#define IS_POW2(Value)  ((Value) != 0U && ((Value) & ((Value) - 1U)) ==
+0U)

2. Good to me. I learned this trick when implementing the MtrrLib.

+#define ALIGN_VALUE_ADDEND(Value, Alignment)  (((Alignment) - (Value))
+& ((Alignment) - 1U))

3. Is any other open source project using the same macro for the addend?
This is actually a general question to all new macros.
I would like the macros look familiar to developers from other open source projects.
Good question, I never really saw it. I only came up with it because for the new PE loader, we may align the PE memory within an underaligned buffer, and for that we need the addend. I initially used to align up and then subtract, but I saw this could be simplified with ALIGN_VALUE_ADDEND, which was used in ALIGN_VALUE anyway. If you have a better name, I'll change it.

Best regards,
Marvin


[1] ISO/IEC 9899:2011, 7.19, 3.

[2] ISO/IEC 9899:2011, 6.6, 9.




Join devel@edk2.groups.io to automatically receive all group messages.