What About The Stack?

This lesson addresses how segmentation works in the stack with the help of an example.

We'll cover the following

Thus far, we’ve left out one important component of the address space: the stack. The stack has been relocated to the physical address 28KB in the diagram above, but with one critical difference: it grows backwards (i.e., towards lower addresses). In physical memory, it “starts” at 28KBAlthough we say, for simplicity, that the stack “starts” at 28KB, this value is actually the byte just below the location of the backward growing region; the first valid byte is actually 28KB minus 1. In contrast, forward-growing regions start at the address of the first byte of the segment. We take this approach because it makes the math to compute the physical address straightforward: the physical address is just the base plus the negative offset. and grows back to 26KB, corresponding to virtual addresses 16KB to 14KB; translation must proceed differently.

The first thing we need is a little extra hardware support. Instead of just base and bounds values, the hardware also needs to know which way the segment grows (a bit, for example, that is set to 11 when the segment grows in the positive direction, and 00 for negative). Our updated view of what the hardware tracks is seen in the figure below:

With the hardware understanding that segments can grow in the negative direction, the hardware must now translate such virtual addresses slightly differently.

Example

Let’s take an example stack virtual address and translate it to understand the process.

In this example, assume we wish to access virtual address 15KB, which should map to physical address 27KB. Our virtual address, in binary form, thus looks like this: 1111000000000011 1100 0000 0000 (hex 0x3C00). The hardware uses the top two bits (1111) to designate the segment, but then we are left with an offset of 3KB. To obtain the correct negative offset, we must subtract the maximum segment size from 3KB: in this example, a segment can be 4KB, and thus the correct negative offset is 3KB minus 4KB which equals -1KB. We simply add the negative offset (-1KB) to the base (28KB) to arrive at the correct physical address: 27KB. The bounds check can be calculated by ensuring the absolute value of the negative offset is less than or equal to the segment’s current size (in this case, 2KB).

Get hands-on with 1400+ tech skills courses.