Page 1 of 1

__attribute__ ((aligned()))

Posted: Thu Dec 09, 2004 11:04 pm
by KaylaKaze
Apart from speed purposes, when is it necessary to align variables in PS2 development? I've been wondering if some of my problems I've been having could be from structures taking memory allocated to others because of some way in which the PS2 handles memory blocks, or just not being able to access the data as expected (I first noticed something like this when I had a 14 byte BMP header being reported as 16 bytes by sizeof).

And I know I've been asking a lot of questions lately, but that's what happens when working on a project, I guess.

Posted: Thu Dec 09, 2004 11:45 pm
by pixel
Depends on what you are doing with the data. If it's to be dma-transferred, for example, or if it's to be accessed in asm using lq/sq, it has to be aligned on the corresponding alignment...

Posted: Thu Dec 09, 2004 11:48 pm
by Guest
Well, also structures I think will be aligned, at a minimum, on word boundries. That would explain why your sizeof() operator returns 16 instead of 14. That normally shouldn't make a difference, so long as you aren't expecting something else to be in the next two bytes. Also, depending on any data you are reading, don't forget the role of endianness and byte swapping.

One more thing, the 16 bytes, and word alignment, can be caused by a two byte gap WITHIN the structure, if you have a structure like so:

struct blah
{
u32 foo;
u32 bar;
u16 oog;
// u16 sized gap here
u32 barf;
};

In memory, between oof and barf, there will be a two byte gap, because barf must start on a word boundry.

Posted: Fri Dec 10, 2004 2:15 am
by ooPo
You can stop this alignment, if you really want to, by using the packed attribute.

struct { char tub; int girl; } __attribute__((packed)) tubgirl;

I think its something along those lines.

Posted: Fri Dec 10, 2004 2:19 am
by pixel
Problem is, gcc may fail producing "unaligned" fetching code in the latter example, thus could lead to a loading exception.

Posted: Fri Dec 10, 2004 3:23 am
by mrbrown
pixel wrote:Problem is, gcc may fail producing "unaligned" fetching code in the latter example, thus could lead to a loading exception.
You need to apply the "packed" attribute to each structure member individually. Then GCC will generate the proper unaligned load/store instructions.

Posted: Fri Dec 10, 2004 5:31 am
by ooPo
Well then. I think we all learned our lesson and will never do that again.