[ prev | next | up ]

Word boundary alignment

[from your friendly TA]
> What does "make sure stack is on a word boundary (must be
> multiple of 4)" mean in the specifications for ThreadCreate?
It means that you must ensure that when you're pointing to the top of the stack, the value of the pointer is a multiple of 4. Recall that a pointer is just a number that indexes into linear memory.

Now, why do you want the stack pointer to be a multiple of 4? This has to do with how the SPARC architecture works. In SPARC, you can read/write 32 bits at a time, or 4 bytes, but you can do this only if you read/write at addresses that are multiples of 4. As an example, if addresses 1000-2000 are valid, then you will be able to read/write the 32 bit values at address 1000, 1004, 1008, etc... These kinds of memory references are called "aligned" memory references. What happens if you want to read a 32 bit value at address 1002 (ie: the bytes at addresses 1002, 1003, 1004, 1005). We call this a "misaligned" memory reference. If the SPARC architecture does not support misaligned memory references, then you will get an exception and your program will crash (with the message "Bus error"). Some architectures (I'm not sure if SPARC is included) do support misaligned memory references. In this case, if you would ask to read the word at address 1002, then the processor would first read the word at address 1000, then the one at address 1004, and then combine the high and low two bytes of these two words to give you the answer. As you can see this is very inefficient, as you're doubling the amount of memory references.

[your instructor adds:]

Correct... the SPARC does not support misaligned references. Here's a quick sample program you can try to verify this:

main () {
	char buf[100];
	int *x, *y;

	x = (int *)&(buf[8]);
	*x = 17;
	printf ("on 4-byte aligned boundary, x = %d\n", *x);

	y = (int *)&(buf[1]);
	*y = 23;
	printf ("on non-aligned boundary, y = %d\n", *y);
}
When you run the program, it will give a bus error on the attempt to assign a value to *y.

In any case, whether or not the architecture you are running on supports misaligned reads/writes, you should always make an effort to align your memory references, especially since it is very simple to do. Although the compiler generally takes care of alignment for you, you have to be careful when you're dealing with low level programming, which is the case in this assignment.