PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

datatype misalignment

Ok, I have a quick question.  What causes a datatype misalignment error?  I have gotten several of them (most of which I have found workarounds for), but I have no idea what causes them, so it is simply guessing when it comes to fixing them.  I you know how to fix one, that information would be very helpful too.
simonjacobs · 05 Jan 2002, 17:10 UTC
does it just mean things are not DWORD aligned?

can you give more info on the code that causes the error?
A data type misalignment occurs when you try to read or write data to an address in memory that is not evenly divisible by the length of the data type you are reading/writing.

In the case of a BYTE, you can read or write to any address because all addresses are evenly divisible by 1.  In the case of a WORD you can only read/write to even numbered addresses because a word is 2 bytes long.  In the case of a DWORD you can only read/write to addresses that are evenly divisible by 4 since a DWORD is 4 bytes in length.

Not all processors have this limitation.  The x86 won't generate an alignment exception, but you'll pay a performance penalty for accessing unaligned data (I don't know if the perf hit is still true with the later Intel chips).  Since the majority of the ports to the Pocket PC are from the PC you can run into this quite a bit, especially when reading from packed data files.

The compiler can help you out with this if you tell the compiler that the data addressed by the pointer is unaligned.  Look at the docs for __unaligned keyword.  This will allow your app to run, but at a severe performance penalty when accessing the data through the __unaligned pointer.  A better solution is to change your data file or code so that you are no longer attempting to read/write unaligned data.

Last modification: Digby - 01/05/02 at 15:40:02
I am probably going to get flamed for this but it works for me ;)

In the header file where you think the misalignment is happening include the statement

#pragma pack(2)

I'm not quite sure what it does, but as I said, it works.

Hope this helps
Bad

PS Feel free to flame me for this, but please include an explantion as to why I should not use this :)
My question is, will it slow down the program as much as __unaligned will?Last modification: Rob - 01/06/02 at 06:33:57
Ok, just out of curiosity, will something like this fix it.  I've been trying this, and

original
Code:

byte *P;
p=(byte *)&SomeVar; //SomeVar is an unsigned char [500]
*((ULONG  *)p)++ = b; //where b is an unsigned long.   Error occurs here


New
Code:

byte *p, *pp;
unsigned char spacer[500]; //An aligned variable
p=(byte *)&spacer
pp = (byte *)&SomeVar;
*((ULONG  *)p)++ = b;
pp = p;
simonjacobs · 06 Jan 2002, 08:52 UTC
I dont think that would help.

Why do you need to access that memory as ULONG's, is it really ULONG data or are you just trying to quickly copy 4 chars at a time?

You need to make sure the memory SomeVar is allocated on 4-byte boundaries. Allocate as:

ULONG somevar[size];

Simon, it has to be ULONG, because it is the size of the wad file in bytes (or is that bits? but anyways) and you can get some very big wad files.  I was thinking about making it a 2 byte value, but then I'd still have to change it latter.  I just reallocated SomeVar as a ulong, and lets see what happens.
Ok, I've declared it as ULONG and I still get the error.  Here is a address 0x00e81b26

Here is the exact code
Code:

#define WRITEULONG(p,b)     *((ULONG  *)p)++ = b

char *PutFileNeeded(void)
{
   int   i;
   byte *p;
   char  wadfilename[MAX_WADPATH];

   p=(byte *)&netbuffer->u.serverinfo.fileneeded; //Now declared as ULONG [500], was char [500]
   for(i=0;i<numwadfiles;i++)
   {
       WRITEULONG(p,wadfiles[i]->filesize);            p=(byte *)&netbuffer->u.serverinfo.fileneeded;
       strcpy(wadfilename,wadfiles[i]->filename); //From here on, this stuff isn't imortant.
       nameonly(wadfilename);
       WRITESTRING(p,wadfilename);
       WRITEMEM(p,wadfiles[i]->md5sum,16);
   }
   netbuffer->u.serverinfo.fileneedednum=i;
   return p;
}
Simon, do you have AIM.  If so, I could talk to you, and probably get this prob worked out in like 2 minutes
simonjacobs · 06 Jan 2002, 09:31 UTC
i've got microsoft IM

can i see the declaration of:

netbuffer->u.serverinfo.fileneeded

and try pragma pack 4

also, if this isnt called in your main game loop just use the unaligned flag
what would be the difference between progma pack(2) and pack(4)
Also, lets say I have this

   int  num = *n->num;

Which variable should have the __unaligned flag, and where should I put it?
In Wolf3D there were a couple of bad alignment problems due to the way it was coded. I had to rewrite those routines, assigning data on a byte-for-byte basis, and / or shifting data around to get the desired result. So there may be cases where there is no quick-fix (like setting a pragma).

Dan East
I agree with the pragma, because setting that actually created other errors.  With pragma set, the demo will not run, without pragma, the demo runs fine.  But where do you put __unaligned.  The misalignement appears to be in a loading routine, so the speed should not bee affected too much by putting it there.
simonjacobs · 06 Jan 2002, 09:49 UTC
the pragma pack (number) specifies the byte alignment, and you should be using 4 not 2. It is documented in the help file for evc.

In the code above yoo should have:

__unaligned ULONG *p;

I have no idea why you are declaring p as a pointer to char then casting it to pointer to long each time you use it???
Don't look at me, I didn't code that routine.  I'm just porting it.
simonjacobs · 06 Jan 2002, 09:54 UTC
You lookin at me punk?
:)
Hey guys, would this work __declspec(4) If I'm reading the WinCe help file right, this will ensure that the data is aligned when the var is declared.  I put in 4, since it is a 4 byte variable, but it can be any size.
Ok, I am still getting that error.  Here is the deal, I can get the first pass to go through ok now (by adding some char vars in the structure definition), but the second time through is giving me trouble.  So, I have decided to ask for the help of all you great programmers out there.

Code:
#define WRITEULONG(p,b)     *((ULONG  *)p)++ = b


This is the problem.  The problem (of course) is storing b to *p.  I have tried this…
Code:
WRITEULONG((__unaligned)p, b)


But to no avail.  Would there be a way to rewrite this in asm so that it will always deal with unaligned variables the correct way?  EVC suggested something like this.

Code:
stb r12,0(r11)
rlwinm r10,r12,24,24,31
stb r10,1(r11)
rlwinm r9,r12,16,24,31
stb r9,2(r11)
rlwinm r8,r12,8,24,31
stb r8,3(r11)


Where r12 would hold b and r11 would be p.  I was thinking that I could make this function in a separate file, and then simply link it to the project.  Would this work?  If it would, could you guys help me right it?

Just incase this helps, here is the asm that is currently being conducted with this function
Code:

93:          WRITEULONG((__unaligned)p,wadfiles[i]->filesize);
1803998C   ldr       lr, [sp, #0x88]  ; 0x88 = 136
18039990   mov       r3, lr, lsl #2
18039994   ldr       r2, [pc, #0xC8]  ;  pc+8+200 = 18039A64
18039998   add       r1, r2, r3
1803999C   ldr       r0, [r1]
180399A0   ldr       lr, [r0, #0x1C]  ; 0x1C = 28
180399A4   ldr       r3, [sp]
180399A8   str       lr, [r3] //The error occurs right here
180399AC   ldr       r2, [sp]
180399B0   add       r1, r2, #4
180399B4   str       r1, [sp]

simonjacobs · 06 Jan 2002, 13:16 UTC
can you try this and let me know if it works:

#define UNALIGNED __unaligned

then declare p as:

UNALIGNED ULONG *p;

dont cast p to unaligned as you have in the code above, declare it as unaligned
Simon is on the right track.  You need to declare the pointer as unaligned.

Let's review:  The data misalignment exception occurs when you are trying to read or write data by dereferencing a pointer.  The value of the pointer (NOT THE VALUE OF WHAT IT'S POINTING TO) must be evenly divisible by the length of the data type you are attempting to read or write.  Go back and read what I just typed until you understand it.

It's now your job to find out which pointer is causing the exception and add the __unaligned keyword to the pointer's declaration.  This is easy to do in the debugger because the debugger will break at the point of exception.  Look at the line of code, look for the pointer, look at what type of data it points to, look at its value.  If the pointer value is not evenly divisible by the length of the data, the that's the pointer that needs to be marked as unaligned.

No pragmas.  No ARM assembly.  No casting to ULONGs.  No declspec'ing.  Just simple debugger work to find out where the problem is occurring, then fixing it.


Sometimes I wish I had a version of The Sims that contained characters from these forums.  I could just watch them run around in circles on the screen instead of getting a headache from trying to understand these posts.  It's like, "My car just broke down... I'll make a big bowl of potato salad and put it on the hood.  Hey! My car still doesn't run!!!  I must have used the wrong type of potatoes?"

There were several datatype misalignment issues with Wolf3D. id Software packed their data files tight, so that some words were not aligned on an even byte boundery. I simply performed such assignments one byte at a time to solve the alignment issue, in place of casting pointers to words and using assignment.

Dan East
Here is a specific example from the pWolf source. This appears to be exactly the same problem you're encountering, except the code is wrapped in a define. The original code is commented out. My CE alternative is the following 3 lines:
[fixed]
//Dan East: Alignment problems here:
//length = *( ( unsigned short * ) demoptr )++;
length = ( * ( ( unsigned char * ) demoptr ) ++ );
length |= ( * ( ( unsigned char * ) demoptr ) ++ )<<8;
demoptr++;
[/fixed]

Dan East
Another alignment fix from pWolf, again, almost the exact same thing as the problem you're encountering. This differs from the above example in that it is a 32 bit int instead of a word. "source" is an unsigned char.
[fixed]
#ifndef _WIN32_WCE
expanded = *( long * )source;
source += 4; // skip over length
#else
//Dan East: Workaround for alignment issues
expanded = *source++;
expanded |= ( *source++ ) << 8;
expanded |= ( *source++ ) << 16;
expanded |= ( *source++ ) << 24;
#endif
[/fixed]

Dan East
Thanks Dan, I will try that now.  Digby, I respect your programing skill and knowledge, but I think that you should relax.  I have tried everything with that "__unaligned" definition, and it won't help in this situation.  I just happedened to post an example where I tried casting __unaligned to see if that would help.  But, it failed to change the code at all.  By the way, you should have used muffins.  And, they don't go on the hood of the car, they go in the trunck.
Ok, I get what you are saying Dan.  Your example is just the reverse of mine.  I have to store the value or the ULONG in *p a byte *.  So, here is my thought.

*p ++ = (byte)wadfiles[i]->filesize;
*p ++ = (byte)wadfiles[i]->filesize <<8;
p++;

Only that won't work because *p ++ = (byte)wadfiles[i]->filesize; would try to store everything in *p, not just the lower byte.  But wait, wouldn't I have to do that four times, since p is a byte, but filesize is a ULONG.  Also, p points to the address of a unsigned char[500].  Would that mess it up at all.  I think that we are getting somewhere, but I could still use more help.

simonjacobs · 06 Jan 2002, 20:27 UTC
Rob: Does this work:

unsigned char *p = something;
ULONG temp = wadfiles->filesize;

memcpy(p, &temp, 4);

simonjacobs · 06 Jan 2002, 20:28 UTC
sorry, i'm tired, what i meant was:

memcpy(p,&wadfiles->filesize,4);

simonjacobs · 06 Jan 2002, 20:30 UTC
my theory is that memcpy will take care of the alignment problem :)

i am probably wrong as usual.

it WOULD be funny if all this hassle could have been avoided with a single memcpy command though!
That would work, but the additional overhead of calling memcpy to copy 4 bytes is not worth it. I would (and did) just copy the bytes over one at time.

Dan East
simonjacobs · 06 Jan 2002, 21:45 UTC
sure, i totally agree. but if rob is having difficulty with the btye copy, and this is only being called once in a load file function where the speed penalty is irrelevant maybe its the best solution.

the byte copy is clearly best, and shouldnt be too hard to get working.
Would this help?

*(__unaligned ULONG*)p = wadfiles->filesize;
p += sizeof(ULONG);

The advantage of this is that the compiler generates the code inline to do what Dan did with the shifting and byte loading (stores in your case).


Sorry about my wisecracks before.  I should add to my list of New Year's resolutions to hold off posting a message for 30 mins or so after I type it.  That would make me think twice about posting such drivel.  I suppose I was a bit frustrated that I couldn't seem help you solve your problem when the answer was so obvious to me.

That's cool.  Yeah, guess I was a little frustrated too.  If I hadn't stopped to fix the palette, I probably would have tossed my 720 out the window (In a well protected case of course so it wouldn't get injured).  Let's hope this works.
You can put a fork in this thread because it is done.  Thanks Digby, your last sugestion works like a charm.